首页 > 解决方案 > 无法从根提供程序访问作用域 DbContext

问题描述

我收到这个错误

System.InvalidOperationException:
'无法从根提供程序解析范围服务'LC.Assets.API.ApiDbFullContext'。'

注册DbContextPool

services.AddDbContextPool<ApiDbFullContext>(o => o.UseSqlServer(connString));

ExtensionDbHelper

public class ExtensionDBHelper : DisposableBase, IExtensionDBHelper
{
    public ExtensionDBHelper(IServiceProvider service)
    {
        IHttpContextAccessor http = service.GetRequiredService<IHttpContextAccessor>();
        IHostingEnvironment env = service.GetRequiredService<IHostingEnvironment>();
        IApiFullDbContext db = service.GetRequiredService<ApiDbFullContext>();

        this.DB = db;
        this.Helper = new ApiDbContextHelper(http, db, env);
        this.Worker = new ApiDbUnitOfWork(this.Helper);
    }

    public IApiFullDbContext DB { get; }
    public IApiDbContextHelper Helper { get; }
    public ApiDbUnitOfWork Worker { get; }
}

在 IApplicationBuilderExtension 中使用 LCCors:

public static IApplicationBuilder UseLCCors(this IApplicationBuilder builder, Action<LCCorsOptions> option)
{
    LCCorsOptions opt = new LCCorsOptions();
    option.Invoke(opt);

    IExtensionDBHelper helper = new ExtensionDBHelper(builder.ApplicationServices);
    ICorsOriginHub hub = GenericExpressions.CorsOriginHub(helper.Worker.GetRepo<CorsOriginHub>().DbSet).FirstOrDefault(h => h.Active && h.Version.Equals(opt.Version));

    if (hub == null)
    {
        throw new HubNotFoundException(opt.Version);
    }
    else if (hub.Outdated)
    {
        throw new IncludeHubOutdatedException(opt.Version);
    }

    foreach(ICorsOriginEntry entry in hub.Items.Where(itm => itm.Active))
    {
        builder.UseCors(options => options.WithOrigins(entry.Host).AllowAnyMethod().AllowAnyHeader());
    }

    return builder;
}

标签: c#asp.net-core

解决方案


this solved my issue:

Changing from AddDbContextPool to plain AddDbContext

Altering the code in ExtensionDBHelper to:

IApiFullDbContext db = service.CreateScope().ServiceProvider.GetRequiredService<ApiDbFullContext>();

推荐阅读