Cannot resolve scoped service DbContextOptions

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

Question

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>();
        }

Usage:

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
4
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>();
    }
}
5
1/9/2019 1:54:29 PM


Related Questions





Related

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