突然我的网站无法启动,在解析 IRepoFactory 时无法解析 AssesDbContext。我不确定出了什么问题,因为所有数据库服务都是在配置开始时添加的。
我收到以下错误:
无法从根提供程序解析“SL.Assets.Components.Repo.IRepoFactory”,因为它需要范围服务“SL.Assets.Components.Data.AssetsDbContext”。
配置:
_ = builder.Services
.AddHttpContextAccessor()
.AddTransient<IActionContextAccessor, ActionContextAccessor>()
.AddDbContext<AssetsDbContext>(opt => opt.UseSqlServer(AssetsStatics.ConnectionString))
.AddDbContext<AssetsClientDbContext>(opt => opt.UseSqlServer(AssetsStatics.ClientConnectionString))
.AddTransient<IAssetsDbContext, AssetsDbContext>()
.AddTransient<IAssetsClientDbContext, AssetsClientDbContext>()
.AddTransient<IDbContextAccessor, DbContextAccessor>()
.AddTransient<IAssetsConfigAccessor, AssetsConfigAccessor>()
.AddTransient<IExpressionFactory, ExpressionFactory>()
.AddTransient<IClientExpressionFactory, ClientExpressionFactory>()
.AddTransient<ILocalizationAccessor, LocalizationAccessor>()
.AddTransient<IUtilityAccessor, UtilityAccessor>()
.AddTransient<IUrlHelperFactory, UrlHelperFactory>()
.AddTransient<IRepoFactory, RepoFactory>()
.AddTransient<IExpressionFactory, ExpressionFactory>();
RepoFactory:
public interface IRepoFactory
{
IRepoBase this[RepoType type] { get; }
IRepoCoreBase this[RepoCoreType type] { get; }
}
public class RepoFactory(IHttpContextAccessor httpContext, IActionContextAccessor actionContext, IUrlHelperFactory urlHelper, IExpressionFactory expFact, IAssetsConfigAccessor config, IDbContextAccessor dbContext, IWebHostEnvironment environment) : IRepoFactory
{
public IRepoBase this[RepoType type]
{
get
{
....
}
}
public IRepoCoreBase this[RepoCoreType type]
{
get
{
IRepoCoreBase? result = default;
switch(type)
{
case RepoCoreType.TagHelper:
result = new TagHelperRepo(httpContext, actionContext, environment, config.Assets.Config, urlHelper);
break;
}
return result;
}
}
}
有什么想法吗?
这个中间件组件就是问题所在。我将依赖注入从类构造函数移至 Invoke 方法。
旧:
public sealed class SetSignIn(RequestDelegate next, IRepoFactory repoFactory)
{
public async Task Invoke(HttpContext httpContext)
{
....
}
}
新:
public sealed class SetSignIn(RequestDelegate next)
{
public async Task Invoke(HttpContext httpContext, IRepoFactory repoFactory)
{
....
}
}