gpt4 book ai didi

c# - 如何将 IHttpContextAccessor 注入(inject) Autofac TenantIdentificationStrategy

转载 作者:行者123 更新时间:2023-12-01 19:58:57 25 4
gpt4 key购买 nike

我正在将 Multi-Tenancy 应用程序从 Webapi 迁移到 aspnet core。在 webapi 版本中,我使用 TenantIdentificationStrategy 根据 HttpContext 上的请求路径识别租户。

转向 aspnet core,我能够成功连接 autofac。我无法弄清楚如何连接租户策略。我尝试在 ConfigureServices 中注入(inject) IHttpContextAccessor 作为

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

我的策略如下

public class AssetClassIdentificationStrategy: ITenantIdentificationStrategy {
private readonly IHttpContextAccessor _accessor;
public AssetClassIdentificationStrategy(IHttpContextAccessor httpContextAccessor)
{
_accessor = httpContextAccessor;
}
public bool TryIdentifyTenant(out object tenantId) {
tenantId = null;
var context = _accessor.HttpContext;
if (context != null && context.Request != null )){
var matchRegex = new Regex(@"\/[\d,\.,\w]*\/(\w*)\/.*");
var match = matchRegex.Match(context.Request.Path.ToString());
if (match.Success) {
tenantId = match.Groups[1].Value.ToLower();
}
}
return tenantId != null;
}
}

我看到的是 HttpContextAccessor 被正确注入(inject),其中 HttpContext 始终为 null。因此,没有解决任何 Multi-Tenancy 服务问题。

四处寻找示例,但找不到任何适合该问题的内容。 Autofacv3 中曾经有一个 RequestParameterTenantIdentificationStrategy ,但不再受支持。感谢对此的任何帮助。

编辑修复了代码问题并根据要求添加 Startup.cs。

public class Startup
{
public Startup(IHostingEnvironment env) {
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.Configure<CacheConfig>(Configuration.GetSection("Caching"),false);
services.AddMvc();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<ITenantIdentificationStrategy,AssetClassIdentificationStrategy>();

var builder = new ContainerBuilder();
builder.Populate(services);
builder.RegisterType<TenantInfo>().WithProperty("TenantName", "unknown").As<ITenantInfo>();

var container = builder.Build();

ITenantIdentificationStrategy tenantIdentificationStrategy;
bool isMultiTenant = container.TryResolve(out tenantIdentificationStrategy);

var mtc = new MultitenantContainer(tenantIdentificationStrategy, container);
mtc.ConfigureTenant("pesonalLoans", b => {
b.RegisterType<TenantInfo>().WithProperty("TenantName","pesonalLoans") .As<ITenantInfo>();
});
mtc.ConfigureTenant("retirement", b => {
b.RegisterType<TenantInfo>().WithProperty("TenantName", "retirement").As<ITenantInfo>();
});

return mtc.Resolve<IServiceProvider>();

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
LoggingConfig.Register(Configuration, loggerFactory);
app.UseMvc();
}
}


public class ValuesController : Controller {
private ITenantInfo _tenant;
public ValuesController(ITenantInfo tenant) {
_tenant = tenant;
}

[HttpGet]
public string Get()
{
return _tenant.TenantName;
}
}


public interface ITenantInfo {
string TenantName { get; set; }
}
public class TenantInfo: ITenantInfo
{
public string TenantName { get; set; }
}

编辑3project.json

{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.0-rc2-3002702",
"type": "platform"
},
"Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
"Autofac": "4.0.0-rc2-240",
"Autofac.Multitenant": "4.0.0-beta8-219",
"System.IdentityModel.Tokens.Jwt": "5.0.0-rc2-305061149",
"Autofac.Extensions.DependencyInjection": "4.0.0-rc2-240",
"System.Reflection": "4.1.0-rc2-24027",
"System.Reflection.Primitives": "4.0.1-rc2-24027",
"System.Reflection.Extensions": "4.0.1-rc2-24027",
"System.Reflection.TypeExtensions": "4.1.0-rc2-24027",
"System.Reflection.Emit": "4.0.1-rc2-24027",
"System.Reflection.Context": "4.0.1-rc2-24027",
"System.Reflection.DispatchProxy": "4.0.1-rc2-24027",
"System.Reflection.Emit.ILGeneration": "4.0.1-rc2-24027",
"Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
"Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.Formatters.Json": "6.0.0-rc1-final",
},

"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": {
"version": "1.0.0-preview1-final",
"imports": "portable-net45+win8+dnxcore50"
}
},

"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"dnxcore50",
"portable-net45+win8"
]
}
},

"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},

"runtimeOptions": {
"gcServer": true
},

"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}

最佳答案

目前还没有办法将内容注入(inject)到租户识别策略中,因为该策略本身不经过 DI 管道。

IHttpContextAccessor通常只支持 HttpContextAccessor 无论如何,它是一个单例,并通过从异步/线程本地上下文获取信息来进行操作。您可以在启动时直接使用其中一项来更新您的策略:

var strat = new MyStrategy(new HttpContextAccessor());

请注意,最初提出问题时, Multi-Tenancy 与 ASP.NET Core 交互的方式存在问题 IServiceProvider系统,也就是说,它没有。

从那时起,我们发布了 4.0.0-rc3-309 for the Autofac.Extensions.DependencyInjection package这解决了这个问题。

变化是您需要更新ConfigureServicesreturn new AutofacServiceProvider(mtc); 并且不再这样做return mtc.Resolve<IServiceProvider>(); .

关于c# - 如何将 IHttpContextAccessor 注入(inject) Autofac TenantIdentificationStrategy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com