نموذج أساسي لـ Nano ASP.NET SaaS
بيانات اعتماد المسؤول (جميع المستأجرين): admin@email.com / Password123!
تتم إعادة تعيين البيانات النموذجية كل ساعة

إنشاء تطبيق متعدد المستأجرين باستخدام Entity Framework Core و ASP.NET – دليل مجاني (الجزء الأول)

رايان لويس
مايو 29, 2023

There is always a point in a software developer’s career where they start to think about building a Software as a Service (SaaS) type platform. A SaaS business model is one where subscribers pay to use the application, each having their own instance, which enables the developer (you) to retire early to a secluded beach in Tahiti and live off the passive income.

The quickest, dirtiest way to achieve this business model from a technical point of view, is to create a separate deployment for each subscriber. This however, is not ideal, because once you have more than a handful of customers, maintaining these separate deployments will quickly turn into a nightmare.

Realistically the only way your dreams of early retirement in the South Pacific will come true is if you implement what’s known as multi-tenant architecture. Multi-tenancy is the concept of having one instance of the application which serves multiple subscribers (tenants), but does so in a way that keeps each tenant’s data completely isolated

In this article, we will look at how we can achieve this type of multi-tenant SaaS architecture with ASP.NET و Entity Framework Core. We will build a simple application step by step. By the end of this tutorial you will understand the fundamentals of how multitenancy works in ASP.NET.

قم بتنزيل finished version here from GitHub

There’s also a الجزء الثاني of this article where we will extend the functionality of this single-database setup to support a hybrid and multiple database setup

While this article is a great way to understand multi-tenant architecture, it’s definitely tricky to code a secure and well architected final solution with identity. The نموذج Nano ASP.NET follows the same fundamentals you will learn here, but adds ASP Identity, clean architecture, and the full gamut of controllers and services you will need to build an app. Instead of spending hours implementing the mundane essentials like user management, authorization, authentication, password resets, etc. check out the boilerplate and get coding the business side of your app sooner than later.

Speaking at a high level, there are two architectures to implement multitenancy:

  • Single Database – Tenant Column Separation
  • Multiple Database – Database per Tenant

The first approach, Single Database, uses one database for all tenants and implements a رقم المستأجر column to keep data separate. Having tables with mixed data might seem like madness when you first consider it, but this is actually the most common approach for achieving multitenancy. With the power of Entity Framework and global query filters, this approach works well and is actually not so complex to implement.

I recommend going the Single Database approach if your business requirements allow it. Granted, if you have legal requirements which dictate that customer data must be totally isolated, then a multi-database approach might be the only choice. Another possible reason you couldn’t use single database might be if your clients use external tools like Power BI that need to connect directly to a database. Allowing them access to a database that contains shared data will not be possible.

The second approach, Multiple Database, is where each tenant has their own database. In both approaches, the first step is to identify the tenants per each request. The database per tenant approach goes a step further by looking up the connection string for the tenant and using that when performing data access. With database per tenant the benefit is that each tenant has their data completely isolated.

While total data separation seems great at first, the added complexity arises when you need to create new tenants and when you need to perform schema updates (migrations). With new tenants, you will need to implement some automation with the infrastructure provider like Azure or AWS, to spin up a new database when you create a new tenant. The other issue is migrations, in that migrations will need to be performed on all the tenant databases whenever you apply new changes to the database.

Lastly, it should be noted that its possible to do a hybrid approach. A hybrid approach is where you store most of the tenants in the main database, and have isolated databases for tenants that require it. This may be beneficial if you have certain tenants that require more data isolation or higher performance requirements, but it does come with all the added complexities of the multiple database approach.

In this tutorial, we are going to implement multi-tenancy with a Single Database with tenant isolation using a رقم المستأجر column. Most SaaS applications you’ve used in the real world, like CRMs, project management apps, PoS systems, etc. use single databases. The single database approach is easier to maintain and if we are going to actually enjoy our early retirement in Tahiti, easy maintenance is essential.

What we are going to build is a Web API, without any user interface, that contains the essential elements of a multi-tenant application.

At a high level, there are three main pieces of the puzzle that make multi-tenancy work.

  • Tenant Identification per each request
  • Ensuring all data is marked with a TenantId
  • Filtering all requests by the TenantId

We will cover each of these points in this tutorial starting with identifying tenants per each request. 

The first piece of the puzzle is identifying tenants per each request. Since middleware runs for every request, and is triggered before reaching any endpoints, its the perfect tool for plucking out a رقم المستأجر from incoming requests.

There are other ways you can present the رقم المستأجر in your requests but the two important ones are:

  • Request Header
  • Token/Cookie Claims

For simplicity, in this tutorial we will use Request headers to identify tenants for all of our requests, but in a real application, you would likely use request headers to identity tenants only on unauthenticated requests. You will want to use Token/Cookie claims for all authenticated requests thereafter. In other words, when a user is trying to login, that is the only time we would look for the tenant Id in the request header. Once they are issued a token/cookie, the tenantId would be contained in that token/cookie and sent up with every request as part of the authentication credentials. 

It’s important to note that in this tutorial, we will not be implementing any authentication or authorization mechanisms. This tutorial is meant to demonstrate the basic concepts of multi-tenant architecture. Once ASP Identity is added into the mix, everything gets a bit more complex. The نموذج Nano ASP.NET however does implement authorization and authentication. It’s the perfect resource to have if you want to see how to secure a multi-tenant application.

Let’s start coding something. We can begin by creating a واجهة برمجة التطبيقات على الويب project. A Web API project only contains REST endpoints, and there’s nothing that resembles a UI – instead we will use ساعي البريد to interact with and test our multi-tenant app. Choose the latest .NET framework, which at the time of this writing is .NET 7, and choose لا شيء for authentication options.

The project we’re creating will contain one entity called المنتج, with one service called المنتجات والخدمات, and one controller called وحدة التحكم في المنتجات. It’s really not even necessary to create a Product Service – we could instead just put all of our business logic in the Products Controller but using the service pattern with dependency injection is good practice. I’ve published other articles that explain interfaces و dependency injection.

The next steps will focus on setting up a basic application with CRUD functionality. Later we will transform this familiar single-tenant app into a multi-tenant one.

We will begin by adding the necessary Nuget packages for إطار عمل الكيانات. Right click on the project in the solution explorer واختر Manage Nuget Packages. There are three that we need to install:

  • Entity Framework Core
  • Entity Framework SqlServer
  • Entity Framework Tools

Next, create a النماذج folder and create a class called ApplicationDbContext. This class should inherit from the DbContext class which is provided by the Entity Framework Core nuget package. Later, we will add a currentTenant service in the ApplicationDBContext. The code should look like this at this point.

عام فئة ApplicationDbContext : DbContext
{

        // منشئ — الاصطلاح المستخدم في Entity Framework 
        عام ApplicationDbContext(خيارات DbContextOptions) : القاعدة(خيارات)
        {
        }
  
}

في appsettings.json file, create an entry for connection strings and name it default connection like this:

  "سلاسل الاتصال": {
    "الاتصال الافتراضي": "مصدر البيانات=(localdb)\\mssqllocaldb؛Database=multiTenantAppDb؛Trusted_Connection=True؛MultipleActiveResultSets=true"
  },

في program.cs add this line to add a database connection as a service to the application:

// إضافة خدمة قاعدة بيانات مع التكوين -- سلسلة الاتصال تُقرأ من ملف appsettings.json
مطور.الخدمات.AddDbContext<ApplicationDbContext> (خيارات => خيارات.UseSqlServer(مطور.الإعدادات.GetConnectionString("الاتصال الافتراضي")));

This is all standard code for any application that is configured to use a database with Entity Framework. Later we will scaffold an initial migration and create a database called multiTenantAppDb.

في النماذج folder, create an interface named يجب أن يكون لدي مستأجر with one property, رقم المستأجر as a سلسلة. This simple interface will serve as a marker for any entities we want to make tenant isolated. It will allow us to iterate over all tenant isolated entities in our application and guarantee that they all contain a رقم المستأجر property.

عام واجهة يجب أن يكون لدي مستأجر
{
    عام سلسلة رقم المستأجر { احصل على؛; تعيين؛; }
}

في النماذج folder, create one entity named المنتج which implements the يجب أن يكون لدي مستأجر interface. Make one of the fields a سلسلة property called رقم المستأجر. We will string IDs like ‘alpha’, ‘beta’, ‘gamma’ for tenants to make things easy to follow along. The Product class should look like this:

عام فئة المنتج : يجب أن يكون لدي مستأجر
{
    عام int المعرّف { احصل على؛; تعيين؛; }
    عام سلسلة الاسم { احصل على؛; تعيين؛; }
    عام عشري السعر { احصل على؛; تعيين؛; }
    عام سلسلة رقم المستأجر { احصل على؛; تعيين؛; }
}

Let’s remember to create a DbSet for our Product entity in the ApplicationDbContext like so:

    عام DbSet<المنتج> المنتجات { احصل على; مجموعة; }

We will return to the ApplicationDbContext later but for now, let’s focus on setting up a working application.

In the same النماذج folder, create another entity named المستأجر with the following properties. There won’t be any relationship between this Tenant entity and any of the other entities in the application. Also, we won’t bother to create a service or a controller for managing tenants, as that’s not the focus of this tutorial. We will instead create them manually in the database. We are going to manually populate the primary keys with string values so add the following code with the data annotations for the ID property:

عام فئة المستأجر
{
    [المفتاح]
    [تم إنشاؤها من قاعدة البيانات(خيار مُنشأ من قاعدة البيانات.لا شيء)]
    عام سلسلة المعرّف { احصل على؛; تعيين؛; }
    عام سلسلة الاسم { احصل على؛; تعيين؛; }
}

إنشاء DbSet for our Tenant entity in the ApplicationDbContext:

    عام DbSet<المستأجر> المستأجرون { احصل على; مجموعة; }

Create a folder called الخدمات in the top level of the application and within that folder, another folder called المنتجات والخدمات. Here we will create a class called المنتجات والخدمات and an interface called IProductService هكذا:

عام واجهة IProductService
{
    IEnumerable<المنتج> GetAllProducts();
    المنتج GetProductById(int id);
    المنتج إنشاء منتج(طلب إنشاء المنتج (CreateProductRequest));
    bool حذف المنتج(int id);
}

Above is the واجهة, and below is the الخدمة that contains our business logic for managing Products

عام فئة المنتجات والخدمات : IProductService
{
    خاص للقراءة فقط ApplicationDbContext _context; // سياق قاعدة البيانات
    عام المنتجات والخدمات(ApplicationDbContext context)
    {
        _السياق = السياق;
    }

    // الحصول على قائمة بجميع المنتجات
    عام IEnumerable<المنتج> GetAllProducts()
    {
        var المنتجات = _السياق.المنتجات.ToList();
        العودة المنتجات;
    }

    // استرداد منتج واحد
    عام المنتج GetProductById(int id)
    {
        var المنتج = _السياق.المنتجات.أين(x => x.المعرّف == id).FirstOrDefault();
        العودة المنتج;
    }

    // إنشاء منتج جديد
    عام المنتج إنشاء منتج(طلب إنشاء المنتج (CreateProductRequest))
    {
        var المنتج = جديد المنتج();
        المنتج.الاسم = طلب.الاسم;
        المنتج.السعر = طلب.السعر;

        _السياق.إضافة(المنتج);
        _السياق.حفظ التغييرات();

        العودة المنتج;
    }


    // حذف منتج
    عام bool حذف المنتج(int id)
    {
        var المنتج = _السياق.المنتجات.أين(x => x.المعرّف == id).FirstOrDefault();

        إذا (المنتج != null)
        {
            _السياق.إزالة(المنتج);
            _السياق.حفظ التغييرات();
            العودة صحيح؛;
        }
        العودة false؛;
    }
}

For the إنشاء method, create a DTO (data transfer object) class for a new product request. In this case, I’ve named mine طلب إنشاء منتج and placed it into a DTOs folder داخل المنتجات والخدمات folder, like so:

    عام فئة طلب إنشاء منتج
    {
        عام سلسلة الاسم { احصل على؛; تعيين؛; }
        عام عشري السعر { احصل على؛; تعيين؛; }
    }

Next, we will need to register the service in the top-level program.cs class as a transient service. We have already configured our database to use ApplicationDBContext مع SqlServer and a connection string which is specified in appsettings.json. The program.cs class should look like this at this point:

باستخدام مايكروسوفت.EntityFrameworkCore;
باستخدام queryFilterApp.النماذج;
باستخدام queryFilterApp.الخدمات.المنتجات والخدمات;

var مطور = تطبيق ويب.CreateBuilder(args); // <--- 1. إنشاء «المنشئ» (وفقًا لأعراف ASP.NET)

// الخدمات الافتراضية التي تُضاف عند إنشاء قالب 'مشروع واجهة برمجة تطبيقات الويب'
مطور.الخدمات.إضافة وحدات التحكم();
مطور.الخدمات.إضافة نقاط نهاية واجهة برمجة التطبيقات (API)();

// إضافة خدمة قاعدة بيانات مع التكوين -- سلسلة الاتصال تُقرأ من ملف appsettings.json
مطور.الخدمات.AddDbContext<ApplicationDbContext> (خيارات => خيارات.UseSqlServer(مطور.الإعدادات.GetConnectionString("الاتصال الافتراضي")));

// إضافة خدمتنا الخاصة — يجب تسجيل خدمات CRUD بعمر مؤقت
مطور.الخدمات.AddTransient<IProductService, المنتجات والخدمات>();


var تطبيق = مطور.بناء(); // <--- 2. إنشاء التطبيق (وفقًا لمعايير ASP.NET)


// البرمجيات الوسيطة الافتراضية عند اختيار إنشاء 'مشروع واجهة برمجة تطبيقات ويب'
تطبيق.إعادة التوجيه عبر HTTPS(); 
تطبيق.تفويض الاستخدام(); 
تطبيق.وحدات التحكم في الخرائط();

تطبيق.تشغيل(); // <--- 3. تشغيل التطبيق (وفقًا لمعايير ASP.NET)

Finally, we will create a Products controller with احصل على, منشور, ، و حذف endpoints. The controller will inject an instance of the Product Service as is typically done in ASP.NET applications. Everything up to this point has been standard procedure in setting up a basic ASP.NET application, with the exception of creating a Tenant table. We should run the application to ensure things are working as expected, because in the next steps, we will make this multi-tenant.

    [الطريق("api/[وحدة التحكم]")]
    [ApiController]
    عام فئة وحدة التحكم في المنتجات : قاعدة وحدة التحكم
    {
        خاص للقراءة فقط IProductService _productService; 

        عام وحدة التحكم في المنتجات(IProductService productService)
        {
            _productService = المنتج والخدمة; // إدراج خدمة المنتجات
        }
   
        // الحصول على قائمة المنتجات
        [HttpGet]
        عام IActionResult احصل على()
        {   
            var قائمة = _productService.GetAllProducts(); 
            العودة حسنًا(قائمة);
        }

        // إنشاء منتج جديد
        [HttpPost]
        عام IActionResult منشور(طلب إنشاء المنتج (CreateProductRequest))
        {
            var النتيجة = _productService.إنشاء منتج(طلب);
            العودة حسنًا(النتيجة);
        }

        // حذف منتج باستخدام المعرّف
        [HttpDelete("{id}")]
        عام IActionResult حذف(int id)
        {
            var النتيجة = _productService.حذف المنتج(id);
            العودة حسنًا(النتيجة);
        }

    }

Before we run the application we will need to create an initial migration and run the تحديث قاعدة البيانات command to actually create the database and tables. Note that if you are downloading the sample project on GitHub, the initial migration has already been created, and all you need to do is run the تحديث قاعدة البيانات command in the وحدة التحكم في إدارة الحزم.

افتح SQL Server Management Studio (SSMS) or the Database Explorer in visual studio to view the database. If everything has gone correctly, there should be new database called multiTenantAppDb with a المنتجات table and a المستأجرون table.

Multi-Tenant App with Entity Framework

Create a few tenants in the tenants table. In a real multi-tenant application you would of course create a service and a controller with CRUD methods to manage tenants via the API. For the sake of time and simplicity, we will populate tenants manually. If you plan to build a multi-tenant application, the نموذج Nano ASP.NET has everything related to managing tenants and users with roles.

Multi-Tenant App ID

Start by creating a new folder in the application called Middleware. Then create a class called TenantResolver. A class becomes middleware when it follows a particular signature. The middleware signature is defined by passing a RequestDelegate parameter in the constructor.

The code that runs is contained in the Task InvokeAsync method which follows, and in our case, this is how the code will look for our Tenant Resolver middleware:

    عام فئة TenantResolver
    {
        خاص للقراءة فقط RequestDelegate _next;
        عام TenantResolver(RequestDelegate التالي)
        {
            _التالي = التالي;
        }

        // الحصول على معرّف المستأجر من الطلبات الواردة 
        عام غير متزامن المهمة InvokeAsync(HttpContext context, ICurrentTenantService currentTenantService)
        {
            السياق.طلب.العناوين.TryGetValue("المستأجر", خارج var المستأجر من الرأس); // معرّف المستأجر من رأس الطلب الوارد
            إذا (سلسلة.IsNullOrEmpty(المستأجر من الرأس) == خطأ)
            {
                انتظار خدمة المستأجر الحالي.تعيين المستأجر(المستأجر من الرأس);
            }

            انتظار _التالي(السياق);
        }


    }

الـ HttpContext object is an object that contains information about the incoming request, and it’s what we will use to read header values. The خدمة المستأجر الحالي is a scoped service that we will create in the next step, which will be responsible for looking up the tenant in the database to verify they exist. It will also hold onto the tenantId value throughout the request lifecycle.

In the code above, we use the TryGetValue method to see if the request contains a header called tenant, and if it does, we read that value and attempt to set it in the currentTenantService.

If you were building a secure application with authentication, it would be important to read tenant values from the cookie/JWT token first before attempting to read from the header.

The next item on the agenda is to create a CurrentTenantService class and an ICurrentTenantService interface. This is the service that the tenant resolver middleware will rely on to verify the tenant exists in the database and store the current tenant values. It will be invoked on every request. Since the tenant value will need to remain available throughout the entirety of the request lifecycle, this service should be registered with a Scoped lifetime.

In the services folder, create a service called CurrentTenantService. Here is what the code should look like:

عام فئة CurrentTenantService : ICurrentTenantService
    {
        خاص للقراءة فقط TenantDbContext _context;
        عام سلسلة? رقم المستأجر { احصل على؛; تعيين؛; }

        عام CurrentTenantService(TenantDbContext context)
        {
            _السياق = السياق;

        }
        عام غير متزامن المهمة<bool> تعيين المستأجر(سلسلة المستأجر)
        {

            var tenantInfo = انتظار _السياق.المستأجرون.أين(x => x.المعرّف == المستأجر).FirstOrDefaultAsync(); // check if tenant exists
            إذا (tenantInfo != null)
            {
                رقم المستأجر = المستأجر;
                العودة صحيح؛;
            }
            وإلا
            {
                رمي جديد استثناء("Tenant invalid"); 
            }

        }
    }

And here is how the واجهة should look:

    عام واجهة ICurrentTenantService
    {
        سلسلة? رقم المستأجر { احصل على؛; تعيين؛; }
        public Task<bool> تعيين المستأجر(سلسلة المستأجر);
    }

The service has one method, which takes a string value – the tenant key, and looks this up in the database to verify that the tenant exists. In a real world application, you would probably check if the tenant has a valid subscription, what their membership level is, etc. If the tenant exists, the value is stored as the رقم المستأجر property which remains available throughout the request lifecycle anywhere else in the application – most importantly, in the ApplicationDbContext.

As we will see in the next steps, this service is invoked in the ApplicationDbContext and the رقم المستأجر property will be read every time something is saved in the database. Now, considering that the CurrentTenantService needs a context class to look up tenants in the database, and the ApplicationDbContext will invoke the CurrentTenantService every time it’s constructed, we will get a circular logic error if we try to use ApplicationDbContext في CurrentTenantService.

Take a closer look at the code for the CurrentTenantService and you will notice that we are using a separate context called TenantDbContext to access the database. By creating a separate context for looking up tenants at the start of the request, we’ll avoid circular logic errors. This by the way, is rarely explained in other tutorials on building multi-tenant apps because most of them don’t show you how to store tenant information in a database. Since we definitely want to store tenant information in a database and not in something like a JSON file, let’s create the TenantDbContext.

We’ll need to create a separate context class for looking up tenant info as the requests come in. This context class will only contain one DbSet, المستأجرون, and will not invoke any services in its constructor. So in other words, its a very basic context! Here’s how the code should look:

  عام فئة TenantDbContext : DbContext
    {
        // This context is for looking up the tenant when a request comes in.
        عام TenantDbContext(خيارات DbContext<TenantDbContext> خيارات)
        : القاعدة(خيارات)
        {
        }

        عام DbSet<المستأجر> المستأجرون { احصل على؛; تعيين؛; }

    }

Now that our project contains multiple context classes, we will need to take some extra steps when running migrations and applying database changes. When you run the إضافة عملية ترحيل أو تحديث قاعدة البيانات commands in وحدة التحكم في إدارة الحزم, you’ll need to specify which context to use. Just write -Context ApplicationDbContext after the commands like this:

إضافة-الهجرة -Context ApplicationDbContext
تحديث-قاعدة البيانات -Context ApplicationDbContext

TenantDbContext will not be used for migrations, for migrations we’ll use the main context, ApplicationDbContext. When adding new entities, you should only add the مجموعات قواعد البيانات إلى ApplicationDbContext – TenantDbContext only needs to be aware of the المستأجرون table.

At this point, we have completed the first piece of the puzzle in building a multi-tenant application. For every incoming request, our middleware is reading a tenant value from the request header and storing that value in our CurrentTenantService.

The place we need to use that current رقم المستأجر is in the ApplicationDbContext. When we are saving entities, we will write that value to the entity being saved if the entity is of type يجب أن يكون لدي مستأجر. This is the second piece of the puzzle and it looks like this:

عام فئة ApplicationDbContext : DbContext
    {
        خاص للقراءة فقط ICurrentTenantService _currentTenantService;
        عام سلسلة معرّف المستأجر الحالي { احصل على؛; تعيين؛; }

        // مُنشئ 
        عام ApplicationDbContext(ICurrentTenantService currentTenantService, خيارات DbContext<ApplicationDbContext> خيارات) : القاعدة(خيارات)
        {
            _currentTenantService = خدمة المستأجر الحالي;
            معرّف المستأجر الحالي = _currentTenantService.رقم المستأجر;
        }

        // DbSets -- create for all entity types to be managed with EF
        عام DbSet<المنتج> المنتجات { احصل على؛; تعيين؛; }
        عام DbSet<المستأجر> المستأجرون { احصل على؛; تعيين؛; }

        // عند حفظ التغييرات - كتابة معرّف المستأجر في الجدول
        عام تجاوز int حفظ التغييرات()
        {        
            foreach (var المدخل في ChangeTracker.المدخلات<يجب أن يكون لدي مستأجر>().ToList()) 
            {
                مفتاح (المدخل.الولاية)
                {
                    حالة حالة الكيان.تمت الإضافة:
                    حالة حالة الكيان.تم تعديله:
                        المدخل.الكيان.رقم المستأجر = معرّف المستأجر الحالي; 
                        فاصل؛;
                }
            }
            var النتيجة = القاعدة.حفظ التغييرات();
            العودة النتيجة;
        }
    }

The first important change is to instantiate the CurrentTenantService in the constructor of ApplicationDbContext. We will also read the رقم المستأجر property of that service in the constructor, and store it as a local value in ApplicationDbContext.

Next, we will add an تجاوز إلى حفظ التغييرات method. The code here is checking for any entities that are of type يجب أن يكون لدي مستأجر, and writing the current رقم المستأجر value for those entities whenever they are saved or modified.

Using a marker interface like يجب أن يكون لدي مستأجر is especially useful in a case like this because all we have to do is implement that interface on any entity we want to be tenant isolated. You could have some entities that are not tenant isolated like static data (country lists for example) and these entities will not be subjected to any on save changes automation.

Now all will need to do is add a أين clause like x=>x.TenantId == currentTenantService.TenantId anywhere we have a احصل على request, right? We’ll also need to instantiate the خدمة المستأجر الحالي in every controller with a get statement, right? Thankfully no, that would be extremely uncool and repetitive. The answer is that there is a better way called global query filtering, which we will implement next.

For the final piece of the puzzle, we want to filter every query whenever we read data. At this point, we can guarantee that any entity of type يجب أن يكون لدي مستأجر will have a رقم المستأجر column with a value of the tenant that created it.

In order to avoid the repetitive madness of adding Where clauses everywhere, we will add an OnModelCreating override method in ApplicationDbContext and use a Query Filter. The final rendition of the ApplicationDbContext code should look as follows:

عام فئة ApplicationDbContext : DbContext
    {
        خاص للقراءة فقط ICurrentTenantService _currentTenantService;
        عام سلسلة معرّف المستأجر الحالي { احصل على؛; تعيين؛; }

        // مُنشئ 
        عام ApplicationDbContext(ICurrentTenantService currentTenantService, خيارات DbContext<ApplicationDbContext> خيارات) : القاعدة(خيارات)
        {
            _currentTenantService = خدمة المستأجر الحالي;
            معرّف المستأجر الحالي = _currentTenantService.رقم المستأجر;
        }

        // DbSets -- create for all entity types to be managed with EF
        عام DbSet<المنتج> المنتجات { احصل على؛; تعيين؛; }
        عام DbSet<المستأجر> المستأجرون { احصل على؛; تعيين؛; }

        // On Model Creating - multitenancy query filters 
        محمي تجاوز فارغ OnModelCreating(أداة ModelBuilder)
        {         
            مطور.الكيان<المنتج>().HasQueryFilter(a => a.رقم المستأجر == معرّف المستأجر الحالي); 
        }

        // عند حفظ التغييرات - كتابة معرّف المستأجر في الجدول
        عام تجاوز int حفظ التغييرات()
        {        
            foreach (var المدخل في ChangeTracker.المدخلات<يجب أن يكون لدي مستأجر>().ToList()) 
            {
                مفتاح (المدخل.الولاية)
                {
                    حالة حالة الكيان.تمت الإضافة:
                    حالة حالة الكيان.تم تعديله:
                        المدخل.الكيان.رقم المستأجر = معرّف المستأجر الحالي; 
                        فاصل؛;
                }
            }
            var النتيجة = القاعدة.حفظ التغييرات();
            العودة النتيجة;
        }
    }

الـ OnModelCreating method fires only once, at the time of the application launch. While the model itself is static, the value of معرّف المستأجر الحالي will remain dynamic. In other words, anytime a query is performed, the value of معرّف المستأجر الحالي will be of the current request.

Just like that, we have implemented the third and final piece of the puzzle. You now have a multitenant application. Whenever you add new entities, you’ll need to implement the يجب أن يكون لدي مستأجر interface on them to make them tenant isolated. You’ll also have to add another query filter in the OnModelCreating model because you cannot specify an interface type here.

You could create a fancy extension method to automate the process of adding query filters based on interface type, but that is outside of the scope of this tutorial. Check out the نموذج Nano ASP.NET though if that sounds interesting. The Nano ASP.NET Boilerplate contains an extension method to query filters based on interface type as well as many other useful methods.

At this point the application is complete and we can move on to testing what we’ve created.

افتح ساعي البريد or whatever tool you wish to use for testing and start by creating a few Products. In the العناوين section of the request, create a header called المستأجر and populate the value with one of the tenantIds you created earlier. Here I will create a few products as the beta tenant:

Multi-Tenant App Headers

Above, the header value and below, the Post body:

Multi-Tenant App Body

After you create a few products for each tenant, the database المنتجات table will look like this

Multi-Tenant App Products table

الـ رقم المستأجر field should be populated with the values of the tenant that created them. Now when we go to retrieve the list of products with a احصل على request, only the products that belong to the specified tenant should be returned. Create a المستأجر header value, just like we did for the منشور request when we created the products, and send the احصل على request.

Alpha Tenant

Above, sending the احصل على request for the alpha tenant. Below, sending the get request for the beta tenant:

Beta Tenant

You should see tenant specific lists of products if everything is working properly. So, if you’ve made it this far congratulations, because you now understand the fundamentals of creating a multi-tenant application with ASP.NET و Entity Framework Core. You have a big step towards building your SaaS app and living the easy life in Tahiti.

If you found this article helpful and want to take it to the next level, you could try to implement authorization و التحقق من الصحة to make it a secure multi-tenant application. As it is now, anyone can change the request header. When you use something like ASP Identity to issue tamper-proof cookies or tokens, you would store the tenant value within those and can reliably validate which tenant is making the request.

في الجزء الثاني of this tutorial series, we will extend this solution to support hybrid and multiple tenant databases.

Please consider buying the Nano ASP.NET SaaS boilerplate to kickstart your next multi-tenant project! You will be supporting this blog and saving yourself a lot of time, even if its just to use as a learning resource. Good luck on whatever path you choose.

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *

هل تحتاج إلى نموذج ASP.NET لإنشاء مشروع MVP القادم؟
تعرّف على مشروع «Nano ASP.NET» النموذجي لخدمات البرمجيات كخدمة (SaaS) متعددة المستأجرين، ووفّر أسابيع أو أشهر من وقت التطوير.
مزيد من المعلومات