无法解析作用域服务 DbContextOptions

Cannot resolve scoped service DbContextOptions

我现在一直在寻找关于这个问题的明确答案,包括 github 但仍然看不出我在这里遗漏了什么:

无法从根提供商解析作用域服务“Microsoft.EntityFrameworkCore.DbContextOptions`1[PureGateway.Data.GatewayContext]”。

在Startup.cs中:

        public void ConfigureServices(IServiceCollection services)
        {
            //other code omitted for brevity

            var connection = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<GatewayContext>(options => options.UseSqlServer(connection));
            services.AddDbContextPool<GatewayContext>(options => options.UseSqlServer(connection));
            services.AddScoped<IGatewayRepository, GatewayRepository>();
        }

用法:

public sealed class MatchBrokerRouteMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<MatchBrokerRouteMiddleware> _logger;

    public MatchBrokerRouteMiddleware(
        RequestDelegate next,
        ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger<MatchBrokerRouteMiddleware>();
    }

    public async Task Invoke(HttpContext context, GatewayContext gatewayContext)
    {
            await _next(context);
    }

我用的是netcore 2.2.

您需要使用 AddDbContextAddDbContextPool,而不是两者都使用。


DbContextPool 需要单个 public 构造函数。检查下面的示例:

public partial class MyDbContext : DbContext
{
    private readonly IUserResolverService _userResolverService;

    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
        _userResolverService = this.GetService<IUserResolverService>();
    }
}

如果你真的需要它那么你可以,我们的想法是再次注册为最后一行数据库选项,因为 AddPooledDbContextFactory 会清理它。并且不要忘记在 DbContext 中只保留 1 个构造函数(只有这个:public MyDbContext(DbContextOptions options) : base(options)):

DbContextOptionsBuilder MsSQL(DbContextOptionsBuilder builder) =>
                builder.UseSqlServer(settings.ConnectionString, x => x.UseNetTopologySuite());
services
    .AddPooledDbContextFactory<MyDbContext>(options => MsSQL(options))
    .AddDbContext<MyDbContext>(options => MsSQL(options))
    .AddScoped<IMyDbContext>(provider => provider.GetService<MyDbContext>())
    .AddSingleton(factory => MsSQL(new DbContextOptionsBuilder()).Options);

我遇到了同样的错误,但发现问题与 DbContextOptions 对象的服务生命周期有关。默认情况下它是“Scoped”(即为每个请求创建),而工厂期望它是单例的。

根据 ,修复是显式设置选项生命周期:

services.AddDbContext<GatewayContext>(options => ApplyOurOptions(options, connectionString),
    contextLifetime: ServiceLifetime.Scoped, 
    optionsLifetime: ServiceLifetime.Singleton);