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

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

You can find the sample code for this post here

In the previous part of the this tutorial we saw how we could do some very basic Tenant resolution. We were identifying who the current tenant is based on values available in the URL such as port number etc. In this post, we will see how we can also use values not available in the URL such as a cookie value (or anything else), to identify the current tenant also.

Tenant Identification

When a request is received, dotnettency creates an identifier that indicates the current tenant. By default, the identifier is based on the request url. However we can override this.

First, derive from HttpContextTenantDistinguisherFactory<TTenant> and override GetTenantDistinguisher:

 1    public class CookieTenantDistinguisherFactory : HttpContextTenantDistinguisherFactory<Tenant>
 2    {
 3        public CookieTenantDistinguisherFactory(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
 4        {
 5        }
 6
 7        protected override TenantDistinguisher GetTenantDistinguisher(HttpContext context)
 8        {
 9            // We will return the request uri by default to identify the tenant,
10            // unless a tenant cookie is available, in which case we will return a URI with a custom scheme.
11            var uri = context.Request.GetUri();
12
13            var cookie = context.Request.Cookies["tenant"];
14            if (!string.IsNullOrWhiteSpace(cookie))
15            {
16                switch (cookie)
17                {
18                    case "Moogle":
19                        return new TenantDistinguisher(new Uri("tenant://Moogle"));
20
21                    case "Gicrosoft":
22                        return new TenantDistinguisher(new Uri("tenant://Gicrosoft"));
23                }
24            }
25
26            return uri;
27        }
28    }

Notice how, when a cookie is present, we return a URI with our own custom scheme - i.e tenant:// and with a hostname that indicates the tenant specified by the cookie.

Next, get dotnettency use our new implementation, in startup.cs:

1            services.AddMultiTenancy<Tenant>((multiTenancyOptions) =>
2            {
3                multiTenancyOptions
4                    .DistinguishTenantsWith<CookieTenantDistinguisherFactory>()
5                    .InitialiseTenant<TenantShellFactory>();
6            });

Now lastly, we need to adjust our TenantShellFactory to handle our custom URI’s:

 1    public class TenantShellFactory : ITenantShellFactory<Tenant>
 2    {
 3        public Task<TenantShell<Tenant>> Get(TenantDistinguisher distinguisher)
 4        {
 5            // If cookie was present, then scheme will be our own custom one.         
 6            if (distinguisher.Uri.Scheme == "tenant")
 7            {
 8                var tenant = distinguisher.Uri.Host.ToLowerInvariant();
 9                switch (tenant)
10                {
11                    case "moogle":
12                        return CreateMoogleTenant();
13                    case "gicrosoft":
14                        return CreateGicrosoftTenant();
15                }
16
17            }
18
19            // Otherwise, just pick tenant based on port as before.
20            if (distinguisher.Uri.Port == 5000 || distinguisher.Uri.Port == 5001)
21            {
22                return CreateMoogleTenant();
23            }
24
25            if (distinguisher.Uri.Port == 5002)
26            {
27                return CreateGicrosoftTenant();
28            }
29
30
31            throw new NotImplementedException("Please make request on ports 5000 - 5003 to see various behaviour.");
32
33        }
34
35        private Task<TenantShell<Tenant>> CreateGicrosoftTenant()
36        {
37            Guid tenantId = Guid.Parse("b17fcd22-0db1-47c0-9fef-1aa1cb09605e");
38            var tenant = new Tenant(tenantId, "Gicrosoft");
39            var result = new TenantShell<Tenant>(tenant);
40            return Task.FromResult(result);
41        }
42
43        private Task<TenantShell<Tenant>> CreateMoogleTenant()
44        {
45            Guid tenantId = Guid.Parse("049c8cc4-3660-41c7-92f0-85430452be22");
46            var tenant = new Tenant(tenantId, "Moogle");
47            // Also adding any additional Uri's that should be mapped to this same tenant.
48            var result = new TenantShell<Tenant>(tenant, new Uri("http://localhost:5000"),
49                                                         new Uri("http://localhost:5001"));
50            return Task.FromResult(result);
51        }
52    }
53
54 

Seeing it in action

Now to see this in action, install your favourite cookie editing tool in your browser. I personally use EditThisCookie

Start the application running and browse on localhost:5000 and you will see:

dotnettency-helloworld-moogle.PNG

Now, add a cookie named “tenant” with a value “Gicrosoft”. Refresh the page:

dotnettency-cookie-gicrosoft.PNG

Hurray! It works! (If it doesn’t, then you can compare against the sample code here)

What’s next?

Stay tuned for:

  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