首页 > 解决方案 > 如何在 Autofac 多租户中使用 IHttpContextAccessor?

问题描述

使用 Autofac 将 IHttpContextAccessor 传递到多租户策略的正确方法是什么?我似乎在任何地方都找不到这个记录。我尝试构建 HttpContextAccessor 的实例并将其传递给策略,但这导致HttpContext始终为空。

启动

public IServiceProvider ConfigureServices(IServiceCollection services) {
    services.AddMvc();
    var builder = new ContainerBuilder();
    builder.Populate(services);

    var container = builder.Build();
    var strategy = new FooTenantStrategy(new HttpContextAccessor());
    var mtc = new MultitenantContainer(strategy, container);
    Startup.ApplicationContainer = mtc;
    return new AutofacServiceProvider(mtc);
}

程序

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        // This enables the request lifetime scope to be properly spawned from
        // the container rather than be a child of the default tenant scope.
        // The ApplicationContainer static property is where the multitenant container
        // will be stored once it's built.
        .UseAutofacMultitenantRequestServices(() => Startup.ApplicationContainer)
        .UseStartup<Startup>();

标签: asp.net-coredependency-injectionautofacmulti-tenant

解决方案


在挖掘了一些源代码后,我从一个测试中找到了一个可以解决问题的示例:

var strategy = new FooTenantStrategy(container.Resolve<IHttpContextAccessor>(), container.Resolve<ILogger<SonicFoundryTenantStrategy>>());

关键部分是从先前构建的容器中提取上下文。


推荐阅读