如何在 Autofac Multitenant 中使用 IHttpContextAccessor?
How to use IHttpContextAccessor in Autofac Multitenant?
使用 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>();
在深入研究了一些源代码后,我发现 sample 来自测试的技巧:
var strategy = new FooTenantStrategy(container.Resolve<IHttpContextAccessor>(), container.Resolve<ILogger<SonicFoundryTenantStrategy>>());
关键部分是从之前构建的容器中提取上下文。
使用 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>();
在深入研究了一些源代码后,我发现 sample 来自测试的技巧:
var strategy = new FooTenantStrategy(container.Resolve<IHttpContextAccessor>(), container.Resolve<ILogger<SonicFoundryTenantStrategy>>());
关键部分是从之前构建的容器中提取上下文。