Search code examples
c#.netasp.net-coreentity-framework-core.net-9.0

Cannot resolve scoped service 'xx.IEnumerable`1[xx.IDbContextOptionsConfiguration`1[xx.ExampleDbContext]]...' after upgrading from .NET 8 to .NET 9


I recently upgraded my project from .NET 8 to .NET 9, and I encountered the following error when running my application:

Cannot resolve scoped service 'System.Collections.Generic.IEnumerable`1[Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptionsConfiguration`1[TestEFCore9Worker.Context.ExampleDbContext]]' from root provider.

error detail

Context: I'm using EF Core for database access. My ExampleDbContext is registered in the ServiceCollection using the following configuration in Program.cs:

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<Worker>();

builder.Services.AddDbContextFactory<ExampleDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnectionString"));
});

builder.Services.AddDbContext<ExampleDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnectionString"));
});

var host = builder.Build();
host.Run();

Below is the constructor of my ExampleDbContext. File ExampleDbContext.cs

public class ExampleDbContext : DbContext
{
    public ExampleDbContext(DbContextOptions options) : base(options)
    {
    }

    public required virtual DbSet<ExampleModel> Examples { get; set; }
}

In Worker.cs

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public Worker(ILogger<Worker> logger, IServiceScopeFactory serviceScopeFactory)
    {
        _logger = logger;
        _serviceScopeFactory = serviceScopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            }

            using (IServiceScope serviceScope = _serviceScopeFactory.CreateScope())
            {
                var dbContextFactory = serviceScope.ServiceProvider.GetRequiredService<IDbContextFactory<ExampleDbContext>>();
                using var dbContext = dbContextFactory.CreateDbContext();

                var exampleModel = new ExampleModel { Name = Guid.NewGuid().ToString() };

                dbContext.Examples.Add(exampleModel);

                dbContext.SaveChanges();
            }

            await Task.Delay(1000, stoppingToken);
        }
    }
}

The application was working perfectly in .NET 8, but after upgrading to .NET 9, this error started appearing. I suspect it might be related to changes in Dependency Injection or EF Core configuration. Could someone help identify the root cause and suggest a solution?

UPDATE: I have edited the question to include the example mentioned by @Guru Stron below. I noticed that if I remove AddDbContext in Program.cs, the error no longer occurs. However, I don’t understand why, as in .NET 8, I used both without any issues.


Solution

  • TL;DR

    Remove the AddDbContext since it is not needed (or AddDbContextFactory if you actually do not need the factory =).

    Details

    I was able to repro the issue, not sure what has changed between the versions but arguably it does not actually matter, the thing is that AddDbContextFactory actually registers the context itself, there is no need to call AddDbContext (though AddDbContextFactory does not check presence of the ctor with options), so just remove the call:

    builder.Services.AddHostedService<Worker>();
    
    builder.Services.AddDbContextFactory<ExampleDbContext>(options =>
    {
        options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnectionString"));
    });
    
    var host = builder.Build();
    

    Also since you are manually creating the scope, in general there is no need to use factory in the provided code, just resolve the context itself:

    using (IServiceScope serviceScope = _serviceScopeFactory.CreateScope())
    {
        var dbContext = serviceScope.ServiceProvider.GetRequiredService<ExampleDbContext>();
    
        var exampleModel = new ExampleModel { Name = Guid.NewGuid().ToString() };
    
        dbContext.Examples.Add(exampleModel);
    
        dbContext.SaveChanges();
    }
    

    The IDbContextOptionsConfiguration was added in .NET 9 and seems to cause such regression.

    Also seems to be related - Cannot remove DBContext from DI