如何在Autofac Multitenant中使用IHttpContextAccessor?

时间:2019-07-23 16:37:06

标签: asp.net-core dependency-injection autofac multi-tenant

使用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>();

1 个答案:

答案 0 :(得分:0)

在仔细研究了一些源代码之后,我从一个能完成窍门的测试中发现了sample

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

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