Autofac MultiTenant - how do I route to a subdomain?

不打扰是莪最后的温柔 提交于 2019-12-03 21:45:14

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!