无法解析作用域服务DbContextOptions

时间:2019-01-09 13:41:33

标签: c# asp.net-core dependency-injection entity-framework-core middleware

我现在一直在寻找关于这个问题的明确答案,包括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。

3 个答案:

答案 0 :(得分:5)

您需要使用AddDbContextAddDbContextPool,而不必同时使用两者。


DbContextPool需要单个公共构造函数。在下面查看我的示例:

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

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

答案 1 :(得分:3)

如果你真的需要它,那么你可以,这个想法是再次注册为最后一行 DB 选项,因为 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);

答案 2 :(得分:2)

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

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

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