无法解析作用域服务DbContextOptions

Ibr*_*taz 4 c# dependency-injection middleware entity-framework-core asp.net-core

我现在一直在寻找有关此问题的明确答案,包括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>();
        }
Run Code Online (Sandbox Code Playgroud)

用法:

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);
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用netcore 2.2。

Mar*_*man 13

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

根据这个 SO 答案,解决方法是显式设置选项生命周期:

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


Der*_*ğlu 5

您要么需要使用AddDbContext要么AddDbContextPool,要么都不需要。


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

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

    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
        _userResolverService = this.GetService<IUserResolverService>();
    }
}
Run Code Online (Sandbox Code Playgroud)