ASP.NET Core 站点无法启动,因为即使将其添加到服务中,它也无法解析数据库上下文

问题描述 投票:0回答:1

突然我的网站无法启动,在解析 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;
        }
    }
}

有什么想法吗?

c# asp.net-core dependency-injection configuration
1个回答
0
投票

这个中间件组件就是问题所在。我将依赖注入从类构造函数移至 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)
    {
        ....
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.