Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot resolve scoped service DbContextOptions

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.

like image 394
IbrarMumtaz Avatar asked Jan 09 '19 13:01

IbrarMumtaz


2 Answers

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>();
    }
}
like image 194
Derviş Kayımbaşıoğlu Avatar answered Sep 20 '22 14:09

Derviş Kayımbaşıoğlu


I had this same error but found the issue was to do with service lifetime of the DbContextOptions object. By default it is "Scoped" (ie created for each request), whereas the factory expects it to be singleton.

As per this SO answer, the fix was to explicitly set the options lifetime:

services.AddDbContext<GatewayContext>(options => ApplyOurOptions(options, connectionString),
    contextLifetime: ServiceLifetime.Scoped, 
    optionsLifetime: ServiceLifetime.Singleton);
like image 36
Mark Foreman Avatar answered Sep 20 '22 14:09

Mark Foreman