asp.net-core - 如何在 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>();
解决方案
在挖掘了一些源代码后,我从一个测试中找到了一个可以解决问题的示例:
var strategy = new FooTenantStrategy(container.Resolve<IHttpContextAccessor>(), container.Resolve<ILogger<SonicFoundryTenantStrategy>>());
关键部分是从先前构建的容器中提取上下文。
推荐阅读
- batch-file - 如何使用 Type 和 Batch 链接源和目标
- regex - 使用 Bash 将字符串添加到正则表达式匹配
- pandas - Pandas TypeError:“numpy.int64”对象不可调用
- java - 无法解决 Gradle 6.4 中的警告
- ruby - 使用 Ruby 类创建哈希
- java - timer.cancel() 是否将计时器返回为空?
- c# - 将 DLLImport 与 dnlib 一起使用
- javascript - lodash 在对象数组中搜索文本
- visual-studio - 在 Visual Studio 中,环境变量在哪里定义?
- ms-access - 如何在访问数据库报告上创建关闭按钮