Modular Multi-tenant ASP.NET Core Application with Dotnettency - Part 1

This is part of a series. You can find the other parts here

You can find the sample code for this post here

In this first part of the tutorial, we will create a shiny new asp.net core project that we will use moving forwards. We will then add some very basic multi-tenancy! We will expand on this in future posts. Before starting this tutortial, you may wish to read to the introduction although this isn’t a necessity. Ok if you are ready, let’s dive in!

Project Setup

Open VS2017 and create a new “empty” ASP.NET Core Web project:

new-aspnetcore-project.PNG

Add the dotnettency nuget package:

neget-dotnettency.PNG

In Program.cs allow kestrel to listen / bind to multiple ports.

 1        public static void Main(string[] args)
 2        {
 3            var host = new WebHostBuilder()
 4                .UseKestrel()
 5                .UseContentRoot(Directory.GetCurrentDirectory())
 6                .UseIISIntegration()
 7                .UseStartup<Startup>()
 8                .UseUrls("http://*:5000", "http://*:5001", "http://*:5002", "http://*:5003")
 9                .Build();
10
11            host.Run();
12        }

Create a class to represent the Tenant. It can have whatever properties you feel are useful:

 1    public class Tenant
 2    {
 3        public Tenant(Guid tenantGuid, string name)
 4        {
 5            TenantGuid = tenantGuid;   
 6            Name = name;                 
 7        }
 8      
 9        public Guid TenantGuid { get; set; }
10        public string Name { get; set; }
11    }

Now that we have our tenant, we need to create a class that dotnettency will use when it needs to load our tenant. Create a class that implements ITenantShellFactory<TTenant>:

 1    public class TenantShellFactory : ITenantShellFactory<Tenant>
 2    {
 3        public Task<TenantShell<Tenant>> Get(TenantDistinguisher distinguisher)
 4        {
 5            if (distinguisher.Uri.Port == 5000 || distinguisher.Uri.Port == 5001)
 6            {
 7                Guid tenantId = Guid.Parse("049c8cc4-3660-41c7-92f0-85430452be22");
 8                var tenant = new Tenant(tenantId, "Moogle");
 9                // Also adding any additional Uri's that should be mapped to this same tenant.
10                var result = new TenantShell<Tenant>(tenant, new Uri("http://localhost:5000"),
11                                                             new Uri("http://localhost:5001"));
12                return Task.FromResult(result);
13            }
14
15            if (distinguisher.Uri.Port == 5002)
16            {
17                Guid tenantId = Guid.Parse("b17fcd22-0db1-47c0-9fef-1aa1cb09605e");
18                var tenant = new Tenant(tenantId, "Gicrosoft");
19                var result = new TenantShell<Tenant>(tenant);
20                return Task.FromResult(result);
21            }
22
23
24            throw new NotImplementedException("Please make request on ports 5000 - 5003 to see various behaviour.");
25
26        }

In our implementation above, we return Moogle when accessed on ports 5000 or 5001, and Gicrosoft when accessed on port 5002. If we are accessed under anything else (e.g port 5003) then we throw an exception for the time being. We will see in a future a couple of different options for handling unknown tenants.

When returning Moogle, we are also including other Uri’s that should be automatically resolved to this Tenant.

The TenantDistinguisher is just a wrapper around a Uri and captures information about the current request by default (host, port, scheme etc). If this is not sufficient for your purposes (e.g perhaps you need to differentiate tenant’s based on a cookie value or something) then this can be tailored to your precise needs, and we will look a that in a future post.

In Startup.cs, add a using statement for dotnettency:

1using Dotnettency;

In ConfigureServices:

1        public void ConfigureServices(IServiceCollection services)
2        {
3            services.AddMultiTenancy<Tenant>((multiTenancyOptions) =>
4            {
5                multiTenancyOptions
6                    .InitialiseTenant<TenantShellFactory>();
7            });
8        }

In Configure we want to UseMultitenancy to add the dotnettency middleware:

 1        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 2        {
 3            loggerFactory.AddConsole();
 4
 5            if (env.IsDevelopment())
 6            {
 7                app.UseDeveloperExceptionPage();
 8            }
 9
10            app.UseMultitenancy<Tenant>((options) =>
11            {
12                
13            });
14
15            app.Run(async (context) =>
16            {
17                await context.Response.WriteAsync("Hello World!");
18            });
19        }

Now we are all setup, we can have fun actually injecting our Tenant.

Seeing it all in action

Change the app.Run() in startup.cs to this:

1            app.Run(async (context) =>
2            {
3                var tenantTask = context.RequestServices.GetRequiredService<Task<Tenant>>();
4                var tenant = await tenantTask;
5
6                await context.Response.WriteAsync("Hello: " + tenant.Name);
7            });

Now start the project, but before you do, double check you are runing under kestreal, if it says IISExpress then switch it:

dotnettency-pick-kestrelproject.PNG

Now browse to the site on localhost:5000 or 5001 and you will see:

dotnettency-helloworld-moogle.PNG

.. and on 5002 you will see:

dotnettency-helloworld-gicrosoft.PNG

Tenant Injection Options

With this now set up, anywhere in your application (Views, Controllers etc) where you need access to the current Tenant you can inject any of the following:

  • Inject Task<TTenant> which gives you non-blocking access to the current Tenant (recommended)
  • Inject TTenant directly. (Has potential to be blocking so not recommended)
  • Inject ITenantAccessor<TTenant> if you would prefer to inject something more descriptive than Task<TTenant> then inject this. It provides access to the same Task<TTenant> (via a Lazy property) that you can await to get access to the current TTenant.

What Next?

In the next post, I will show you how to extend this sample to identify tenants based on some information that isn’t available from a normal request Uri - like a cookie.

Overall, we still have a lot of dotnettency features to get through in this series. So stay tuned for things like:

  1. Per Tenant Container / Services
  2. Per Tenant Middleware
  3. Per Tenant IHostingEnvironment (for sandboxing file access)
  4. Modules (Shared and Routed)

Don’t forget to leave a comment if you find this stuff useful!

This is part of a series. You can find the other parts here

You can find the sample code for this post here

comments powered by Disqus