【发布时间】:2019-10-07 13:37:30
【问题描述】:
我正在尝试在ConfigureMultitenantContainer 中解析ITenantIdentificationStrategy,但我有An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll。
我已经在ConfigureContainer注册了TenantResolverStrategy:
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<TenantResolverStrategy>().As<ITenantIdentificationStrategy>();
}
我想解析ConfigureMultitenantContainer中的ITenantIdentificationStrategy:
public static MultitenantContainer ConfigureMultitenantContainer(IContainer container)
{
var strategy = container.Resolve<ITenantIdentificationStrategy>();
var mtc = new MultitenantContainer(strategy, container);
// mtc.ConfigureTenant("a", cb => cb.RegisterType<TenantACustom>().As<ITenantCustom>());
return mtc;
}
但是它正在抛出An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll。
我的ITenantIdentificationStrategy是这样实现的:
public class TenantResolverStrategy : ITenantIdentificationStrategy
{
public TenantResolverStrategy(
IHttpContextAccessor httpContextAccessor,
IMemoryCache memoryCache,
TenantEntity tenantEntity
)
{
this.httpContextAccessor = httpContextAccessor;
this.memoryCache = memoryCache;
this.tenantEntity = tenantEntity;
}
public bool TryIdentifyTenant(out object tenantId)
{
tenantId = null;
var context = httpContextAccessor.HttpContext;
var hostName = context?.Request?.Host.Value;
tenantEntity = GetTenant(hostName);
if (tenantEntity != null)
{
tenantId = tenantEntity.TenantCode;
}
return (tenantId != null || tenantId == (object)"");
}
}
我在Program.cs中注册ConfigureMultitenantContainer如下:
var host = Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacMultitenantServiceProviderFactory(Startup.ConfigureMultitenantContainer))
我也无法解决我在ConfigureContainer 中注册的其他依赖项。我的实现有什么问题吗?
【问题讨论】:
-
我怀疑您的某个对象无法解析,这就是问题所在。你能让非多租户容器工作并解决你需要的对象吗?
-
我认为你是对的。我无法解析 DbContext,但我能够解析与 DbContext 无关的其他依赖项。
-
经过进一步检查,如果
ITenantIdentificationStrategy没有与DbContext相关的依赖,则DbContext可以在其他类中解析。由于我需要根据存储在 DbContext 中的主机名来识别租户,我该如何以其他方式做到这一点? -
看错误信息,其实是无法解析DbContextOption。
An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll: 'An exception was thrown while activating WebApi.Saas.TenantResolverStrategy2 -> Data.System.Databases.SystemDbContext -> λ:Microsoft.EntityFrameworkCore.DbContextOptions[[Data.System.Databases.SystemDbContext, Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]。但是我该如何解决呢?
标签: c# dependency-injection autofac ioc-container asp.net-core-3.0