SharedFlat and Databases

Introduction

This post is part of a series on SharedFlat. See here the first (introduction) and here the second (UI). This time I will be explaining how SharedFlat handles multitenant databases.

There are essentially three strategies for doing multitenancy when it comes to databases:

  1. One connection string per tenant, which effectively means a different database for each tenant
  2. One schema per tenant, meaning, one table will exist on a schema for each tenant
  3. A single database where multitenant tables have a column that is used to distinguish tenants

Let’s see how we can have this with SharedFlat! First, it’s needed to say that this uses Entity Framework Core 3.1 and that there is a TenantDbContext abstract class that we should inherit from.

Database per Tenant

Let’s start with database per tenant. In this case, it is expected that we store in the configuration (typically the appsettings.json file) one connection string for each for each tenant. For example:

{ “ConnectionStrings”: {

    “abc”: “<connection string for abc>”,

    “xpto”: “<connection string for xpto>”

}

}

We just need, when registering the services, to use the DifferentConnectionPerTenant extension method:

services

.AddTenantService()

.AddTenantDbContextIdentification()

.DifferentConnectionPerTenant();

And SharedFlat will know what to do. If, for any reason, you wish to use a differently-named connection string, there is an overload that lets you customize this:

services

.AddTenantService()

.AddTenantDbContextIdentification()

.DifferentConnectionPerTenant(options =>

{

options.Mapping[“xpto”] = “xpto2”;

});

Schema per Tenant

Next is different schema per tenant. The extension method to call is DifferentSchemaPerTenant:

services

.AddTenantService()

.AddTenantDbContextIdentification()

.DifferentSchemaPerTenant();

By default, the schema will be identical to the tenant; should we need to change that, there is an overload:

services

.AddTenantService()

.AddTenantDbContextIdentification()

.DifferentSchemaPerTenant(options =>

{

options.Mapping[“xpto”] = “xpto2”;

});

This will set the schema on each entity that implements the ITenantEntity interface (a simple marker interface) when the TenantDbContext -derived class is initialized. To be clear, using SQL Server as an example, it will change the default (“dbo”) for the tenant value, so a table named “dbo.Product” will become “abc.Product”, “xpto.Product”, etc.

Filter by Tenant

The last technique depends on having a column on each table that we want to make multitenant, as dictated by its entity implementing ITenantEntity. The method to call is FilterByTenant, unsurprisingly:

services

.AddTenantService()

.AddTenantDbContextIdentification()

.FilterByTenant();

As is usual, the method has some defaults, like, the name of the column (“Tenant”), but we can change it:

services

.AddTenantService()

.AddTenantDbContextIdentification()

.FilterByTenant(“TenanantCol”);

Or, in the eventual case where you need to change the mapping:

services

.AddTenantService()

.AddTenantDbContextIdentification()

.FilterByTenant(options =>

{

options.Mapping[“xpto”] = “xpto2”;

});

Filtering by tenant means that whenever the context is querying for a multitenant-aware entity, a filter is added:

SELECT p.[ProductId], p.[Name], p.[Price]

FROM [dbo].[Product] p

WHERE p.[Tenant] = ‘abc’

Conclusion

And this is it for multitenant databases. Keep tuned for more on SharedFlat, and, as always, let me hear your thoughts! Winking smile

SharedFlat and Multitenant UI

Introduction

In my previous post, I introduced SharedFlat, a library for making multitenant ASP.NET Core apps easier to build. This time I’m going to talk about how can we customize the UI per tenant.

Using Conditional Logic in Views

One way to make UI modifications is to have conditional logic in views. There is an extension method, IsEnabledForTenant, that can be used to check if a specific property is set to true for the current tenant:

@if (this.IsEnabledForTenant(“Foo”))

{

<p>Bar</p>

}

This will look for an option registered using the Options Pattern that was described in the previous post.

Another option is to check for a specific tenant, using the IsTenant extension method:

@if (this.IsTenant(“abc”))

{

<p>abc</p>

}

For the exact same purpose we can also use the <tenant> tag helper:

<tenant name=”xpto”>

<p>xpto!</p>

</tenant>

If we wish to load a partial view, there’s another tag helper just for that, <tenant-partial>:

<tenant-partial tenant=”xyz” name=”xyzView”></tenant-partial>

This will conditionally load the xyzView file if the current tenant is xyz.

Using Different Files

A different approach would be to have different files (in different folders), one for each tenant. Say, for example, that you want to have a different folder per each tenant in your Views\<controller> folder. You just need to call AddTenantLocations when registering the services:

services

.AddTenantService()

.AddTenantLocations();

After this, if you have this folder structure:

  • Views
    • Home
      • abc
      • xyz

ASP.NET Core will load the views from the tenant-specific folder, (abc or xyz) and only if it cannot find the files there ASP.NET Core will it resort to the default ones (in Home or Shared).

Finally, if you wish to load static files from a well-known location that refers to the tenant, you can do this:

<script src=”~/@this.GetTenant()/index.js”></script>

Conclusion

This is as much as it goes for now for making the UI multitenant with SharedFlat. On the next post I will be talking about data, how to access databases in a multitenant way.

Introducing SharedFlat

Introduction

A multitenant web application is one that responds differently depending on how it is addressed (the tenant). This kind of architecture has become very popular, because a single code base and deployment can serve many different tenants.

There are a few libraries out there that help ASP.NET Core developers implement such architectures, but, since I wrote a book on ASP.NET Multitenant Applications a few years ago, I decided to write something from scratch for ASP.NET Core – and here is SharedFlat!

For the sake of the examples, let’s assume two tenants that correspond to two different domain names, abc.com (abc) and xyz.net (xyz).

Concepts

SharedFlat is available at GitHub and NuGet and you are free to have a look, fork and suggest improvements. It is still in early stages, mind you!

It was designed around the following key tenets:

What is a tenant?

A tenant is a unique entity, identified by a name, and the application must respond appropriately to in, in terms of:

  • User interface: each tenant may have one or more different UI aspects
  • Data: each tenant should have access to different data
  • Behavior: the application should behave (maybe slightly) differently, for each tenant

The current tenant is always returned by the implementation of the ITenantService interface:

public interface ITenantService

{

string GetCurrentTenant();

}

Simple, don’t you think? The returned tenant information is the tenant’s name (or code, if you prefer).

How do we identify a tenant?

Now, the first thing to know is, how do we identify the current tenant? Well, there are different strategies for this, but they all implement this interface:

public interface ITenantIdentificationService

{

string GetCurrentTenant(HttpContext context);

}

The strategies itself can be various:

  • Using the request’s HTTP Host header: useful for scenarios where we have multiple domains pointing to the same IP address and we want to distinguish the tenant by the requested host
  • Using a query string field: more for debugging purposes
  • Using the source IP of the request: for when we want to force IPs to be of a specific tenant
  • Static: for testing purposes only
  • Dynamic: when we decide in code, at runtime, what the tenant is
  • Some header’s value

TenantIdentificationServices

The ITenantService that we saw first will have to somehow delegate to one of these implementations for getting the current tenant. We need to register one implementation by using one of the following extension methods:

services.AddTenantIdentification()

.DynamicTenant(ctx => “abc.com”) //dynamic

.TenantForQueryString() //query string

.TenantForSourceIP() //source IP

.TenantForHost() //host header

.TenantForHeader() //some header

.StaticTenant(“abc.com”); //static

Of course, only one of these methods (DynamicTenant, TenantForQueryString, TenantForSourceIP, TenantForHost, TenantForHeader, StaticTenant) should be called.

Some of these different strategies need configuration. For example, to map a host name to a tenant name, we use code like this:

services.AddTenantIdentification()

.TenantForSourceIP(options =>

{

options.Mapping.Default = “abc”;

options.Mapping

.Add(“192.168.1.0”, “xyz”)

.Add(“10.0.0.0”, “abc”);

});

Some tenant identification services also expose an interface ITenantsEnumerationService, which allows listing all the known tenants (their name, or code). This service can be retrieved from the DI, but only if the registered identification service supports it:

public IActionResult Index([FromServices] ITenantsEnumerationService svc)

{

var tenants = svc.GetAllTenants();

return View(tenants);

}

Configuration per tenant

It is also very important to get different configuration depending on the current tenant. Almost all of the tenant identification strategies (except StaticTenantIdentificationService and DynamicTenantIdentificationService) support a mapping between “something” and a tenant code. This “something” may be the source IP (SourceIPTenantIdentificationService), the request’s Host header (HostTenantIdentificationService), etc. There is a standard configuration section that you can add to your appsettings.json file:

{

“Tenants”: {

“Default”: “”,

“Tenants”: {

“xyz.net”: “xyz”,

“abc.com”: “abc”

}

}

}

You can load the configuration using an extension method:

services.AddTenantIdentification()

.TenantForHost(options =>

{

Configuration.BindTenantsMapping(options.Mapping);

});

Or you can just set the values manually, as we’ve seen before.

If you want to set some per-tenant configuration, you should use the Options Pattern with a named configuration (one per tenant):

services.Configure<SomeClass>(“abc”, options =>

{

options.Foo = “bar”;

});

And then you need to retrieve it like this:

public HomeController(IOptionsSnapshot<SomeClass> optionsSnapshot, ITenantService tenantService)

{

var tenant = tenantService.GetCurrentTenant();

var options = optionsSnapshot.Get(tenant);

//…

}

There is yet another option: you can have a class that implements ITenantConfiguration, which is defined as:

public interface ITenantConfiguration

{

string Tenant { get; }

void ConfigureServices(IConfiguration configuration, IServiceCollection services);

}

You can have one class per tenant and in there you can register services that are specific for it. In order for it to work, you need to call the AddTenantConfiguration extension method:

services.AddTenantIdentification()

.TenantForHost(options =>

{

Configuration.BindTenantsMapping(options.Mapping);

})

.AddTenantConfiguration();

Conclusion

This is all I have for now, stay tuned for more on SharedFlat!