Skip to content

Sample implementation of a multi-tenant ASP.NET Core WebApi application.

Notifications You must be signed in to change notification settings

smurariu/CoreMultitenancy

Repository files navigation

ASP.NET Core Multitenancy Implementation

Goal

Easily inject different concrete implementations of services and different configuration values per tenant.

How to run

cd src

dotnet clean && dotnet pack Multitenancy/ && dotnet build && dotnet test ../test/MultitenantAspApp.Tests/MultitenantAspApp.Tests.csproj && dotnet run --project MultitenantAspApp

You can now check out

http://localhost:5000/XX/api/ValuesWithDependencies

http://localhost:5000/SZ/api/ValuesWithDependencies

http://localhost:5000/XX/api/ValuesWithOptions

http://localhost:5000/SZ/api/ValuesWithOptions

Notice the different outputs per tenant.

How to setup in your project

Step 1:

In your ASP.NET project, take a dependency on the Multitenancy package:

dotnet add package Multitenancy

and, after you setup all your dependencies, setup the overrides/individual dependencies for each of your tenants:

services.ConfigureTenant(t =>
{
    t.TenantId = "SZ";
    t.ServiceCollection.AddTransient<IHelloWorldService, SzHelloWorldService>();

    t.ServiceCollection.Configure<ValuesControllerOptions>(o =>
    {
        o.Value1Value = 42;
        o.Value2Value = "value1_configured_by_delegate_for_SZ";
    });
});

Step 2:

Add the middleware in the Configure method

app.UseMultitenancy();

Step 3:

Add route prefix.

If you wish to be able to pass the string tenantId parameter to your controller actions, you can add a route prefix that identifies the tenant and passes it on to your action methods.

To do this, in your Startup.cs file you have to change the Mvc registration in the ConfigureServices method from

services.AddMvcCore();

to

services.AddMvcCore(o => { o.UseTenantRoutePrefix(); })

You can change the default name of tenantId by calling UseTenantRoutePrefix() with the desired name: UseTenantRoutePrefix("tenantIdentifier").