如何使用Autofac正确配置InstancePerTenant?

时间:2019-11-15 02:18:02

标签: c# autofac asp.net-core-3.0

我一直在尝试使用InstancePerTenant为每个租户设置我的组件实例。但是,InstancePerTenant的行为类似于SingleInstance。我的设置有问题吗?

我有这个ContainerBuilder扩展,可以配置与多租户相关的依赖项。

public static ContainerBuilder AddMultitenancy(this ContainerBuilder builder)
{
  builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
  builder.RegisterType<TenantStore>().As<ITenantStore>().SingleInstance();
  builder.RegisterType<TenantResolverStrategy>().As<ITenantIdentificationStrategy>().SingleInstance();
  return builder
}

租户通过主机名标识:

public class TenantResolverStrategy : ITenantIdentificationStrategy
{
  private readonly IHttpContextAccessor httpContextAccessor;

  public TenantResolverStrategy(
    IHttpContextAccessor httpContextAccessor
  )
  {
    this.httpContextAccessor = httpContextAccessor;
  }

  public bool TryIdentifyTenant(out object tenantId)
  {
    // hostname is the tenantId
    tenantId = httpContextAccessor.HttpContext?.Request?.Host.Value;
    return (tenantId != null || tenantId == (object)"");
  }
}

TenantStore只是一个类,用于根据tenantId(主机名)从数据库中解析租户实体

public class TenantStore : ITenantStore
{
  private readonly ITenantIdentificationStrategy tenantIdentificationStrategy;
  private readonly MemoryCacheStore cacheStore;
  private readonly ITenantService tenantService;

  public TenantStore(
    ITenantIdentificationStrategy tenantIdentificationStrategy,
    MemoryCacheStore cacheStore,
    ITenantService tenantService
  )
  {
    this.tenantIdentificationStrategy = tenantIdentificationStrategy;
    this.cacheStore = cacheStore;
    this.tenantService = tenantService;
  }

  public async Task<TenantEntity> GetTenantAsync(object tenantId)
  {
    var hostName = (string)tenantId;
    var tenant = cacheStore.Get<TenantEntity>(CacheType.Tenant, hostName);

    if (tenant == null)
    {
      tenant = await tenantService.GetTenantByHostNameFromDatabaseAsync(hostName);
      cacheStore.Set(tenant, CacheType.Tenant, hostName);
    }

    return tenant ?? new TenantEntity();
  }
}

在Startup.cs中,我正在TenantSpecific中注册InstancePerTenant

public void ConfigureContainer(ContainerBuilder builder)
{
  builder.AddMultitenancy();
  builder.RegisterType<TenantSpecific>().As<ITenantSpecific>().InstancePerTenant();
}

public static MultitenantContainer ConfigureMultitenantContainer(IContainer container
{
  var strategy = container.Resolve<ITenantIdentificationStrategy>();
  var multitenantContainer = new MultitenantContainer(strategy, container);
  // Nothing important here
  multitenantContainer.RegisterMultitenantSpecificStuff();
  return multitenantContainer;
}

TenantSpecific.cs和TenantSpecificController.cs:

public class TenantSpecific
{
  public Guid Id { get; set; }

  public TenantSpecific()
  {
    this.Id = Guid.NewGuid();
  }
}

public class TenantSpecificController : ApiController
{
  private readonly ITenantSpecific tenantSpecific;

  public TenantSpecificController(ITenantSpecific tenantSpecific)
  {
    this.tenantSpecific = tenantSpecific;
  }

  [HttpGet]
  public IActionResult Get()
  {
    return Ok(tenantSpecific.Id);
  }
}

在Program.cs

public static IHostBuilder CreateHostBuilder(string[] args)
{
  var host = Host.CreateDefaultBuilder(args)
    .UseServiceProviderFactory(new AutofacMultitenantServiceProviderFactory(Startup.ConfigureMultitenantContainer))
    .ConfigureWebHostDefaults(webHostBuilder =>
    {
      webHostBuilder
        .UseConfiguration(ConfigurationModule.GetConfiguration())
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>();
    });
  return host;
}

当我调用http://tenant1.localhost/tenant-specific/http://tenant2.localhost/tenant-specific时,像Singleton一样只调用一次TenantSpecific的构造函数。 tenantSpecific.Id返回相同的值。因此,我假设InstancePerTenant在这里不起作用。

我的设置是否有问题?

1 个答案:

答案 0 :(得分:2)

如文档ASP.net core multitenant support

中所述

您应该添加对AddAutofacMultitenantRequestServices()的调用,以将所需的中间件添加到根容器中,这是多租户工作所必需的。

public void ConfigureServices(IServiceCollection services)
{
    // This will all go in the ROOT CONTAINER and is NOT TENANT SPECIFIC.
    services.AddMvc();
    services.AddControllers();

    // This adds the required middleware to the ROOT CONTAINER and 
    // is required for multitenancy to work.
    services.AddAutofacMultitenantRequestServices();
}