This post is about developing multi-tenant applications with ASP.NET Core. Multi-tenancy is an architecture in which a single instance of a software application serves multiple customers. Each customer is called a tenant. Tenants may be given the ability to customize some parts of the application.
The first aspect of multi-tenancy is tenant identification - identifying tenants based on information available in the current request. This could be the hostname, current user or perhaps HTTP header. In this post I am identifying the tenant based on hostname. I have created ActionFilter, which helps to identify tenants from the Host header. Here is the tenant resolution logic.
And you can use this class as an attribute in controller like this.
If you want to use DbContext in this class, you can inject it via ASP.NET Core DI, by injecting it in the constructor. But if you create a constructor with parameter, you will not be able to use it as attribute in controller. So you need to inject the Filter with other dependencies. And you need to use ServiceFilter attribute to attach this attribute in controller. Here is the modified code.
And here is the startup code.
Next you can decorate controller with service filter attribute.
And you can get the tenant information from RouteData. Right now my tenant class includes only name and host properties. You can include other properties like styles or themes and business rules.
Here is the multi tenant aspnet core running on my system, if you look the URLs, I have two URLs and based on URLs I am changing the Style sheets.