Cannot resolve scoped service DbContextOptions c# dependency-injection entity-framework-core middleware


I been searching around now for a clear cut answer on this issue, including github and still cannot see what I am missing here:

Cannot resolve scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions`1[PureGateway.Data.GatewayContext]' from root provider.

In 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);

I am using netcore 2.2.

1/9/2019 1:41:32 PM

Accepted Answer

you either need to use AddDbContext or AddDbContextPool, not both of them.

DbContextPool needs single public constructor. Check my Example below:

public partial class MyDbContext : DbContext
    private readonly IUserResolverService _userResolverService;

    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        _userResolverService = this.GetService<IUserResolverService>();
1/9/2019 1:54:29 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow