Autofac MultiTenant - how do I route to a subdomai

2020-06-29 06:57发布

问题:

n00b here. Re-asking question because I didn't tag it right.

I am trying to utilize Autofac's MutliTenant feature. I got an example "working" from the source files. I've scanned the docs and am having trouble figuring out how to "route" the tenants.

Currently, I'd like to utilize a single code base for a basic CRUD app. The CRUD app will be used by several different sites, just focused on specific services for the individual site.

I'm wanting to do this eventually:

  • codebase.website1.com (Tenant 1)
  • codebase.website2.com (Tenant 2)
  • codebase.website3.com (Tenant 3)

Any thoughts or references? Thanks.

回答1:

If you check out the Autofac multitenant documentation on the wiki you'll notice that the way you determine the tenant is by implementing an ITenantIdentificationStrategy. There is a sample given on that wiki page showing how to get the tenant from a parameter in the request, like a query string.

It is easy enough to modify the example to look at some other part of the request - the host name, the domain name, or whatever else.

using System;
using System.Web;
using AutofacContrib.Multitenant;

namespace DemoNamespace
{
  public class DomainStrategy : ITenantIdentificationStrategy
  {
    public bool TryIdentifyTenant(out object tenantId)
    {
      tenantId = null;
      try
      {
        var context = HttpContext.Current;
        if(context != null && context.Request != null)
        {
          var site = context.Request.Url.Authority;
          // Here's where you map the site to the tenant ID:
          tenantId = MapTheSiteToTheTenantId(site);
        }
      }
      catch(HttpException)
      {
        // Happens at app startup in IIS 7.0
      }
      return tenantId != null;
    }
  }
}

Obviously you'll need to massage that to work for you. How you do the mapping, whether you return null as the default tenant ID or not, etc.

Note that if you're testing based on an HTTP request value, then any time a dependency is resolved and there is no web context, you're going to get application-level dependencies, not tenant-specific dependencies... because you won't be able to identify the tenant. You see a small artifact of that in the catch block - if any dependencies get resolved at application startup, there's not necessarily a web context so IIS 7.0 throws an HttpException when you call HttpContext.Current. You'll have to test for stuff like that.

Also, you'll want to consider a caching strategy for tenant ID mappings if it's, say, a service call or something expensive. Every time you resolve a multitenant dependency the strategy gets invoked, so you want to make the strategy implementation as efficient as possible.

I would really recommend checking out that documentation. It's long, but that's because multitenancy is a complex topic and there's a lot of ground to cover. If you dive in there, you'll find the answers to questions like this.