admin管理员组

文章数量:1025476

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.

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.

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.

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.

Share Improve this question edited Nov 18, 2024 at 8:47 Guru Stron 145k11 gold badges172 silver badges214 bronze badges asked Nov 17, 2024 at 13:10 ThangLeThangLe 1,0001 gold badge8 silver badges16 bronze badges 4
  • Can you please show the constructors of your CrawlerDbContext class? – Ricardo Peres Commented Nov 17, 2024 at 13:15
  • Hi @RicardoPeres, I updated the post (added picture about my DbContext. Thank you. – ThangLe Commented Nov 17, 2024 at 13:22
  • Do you have a minimal reproducible example you can share? – Guru Stron Commented Nov 17, 2024 at 18:39
  • Hi @GuruStron, thank you. I have updated the question and added more examples. While creating an example, I recognizednthat if I remove AddDbContext from the DI container, the bug disappears. However, I don’t understand why, as in my real project running on .NET 8, I use both AddDbContextFactory and AddDbContext without any issues. – ThangLe Commented Nov 18, 2024 at 4:14
Add a comment  | 

1 Answer 1

Reset to default 9

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

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.

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.

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.

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.

Share Improve this question edited Nov 18, 2024 at 8:47 Guru Stron 145k11 gold badges172 silver badges214 bronze badges asked Nov 17, 2024 at 13:10 ThangLeThangLe 1,0001 gold badge8 silver badges16 bronze badges 4
  • Can you please show the constructors of your CrawlerDbContext class? – Ricardo Peres Commented Nov 17, 2024 at 13:15
  • Hi @RicardoPeres, I updated the post (added picture about my DbContext. Thank you. – ThangLe Commented Nov 17, 2024 at 13:22
  • Do you have a minimal reproducible example you can share? – Guru Stron Commented Nov 17, 2024 at 18:39
  • Hi @GuruStron, thank you. I have updated the question and added more examples. While creating an example, I recognizednthat if I remove AddDbContext from the DI container, the bug disappears. However, I don’t understand why, as in my real project running on .NET 8, I use both AddDbContextFactory and AddDbContext without any issues. – ThangLe Commented Nov 18, 2024 at 4:14
Add a comment  | 

1 Answer 1

Reset to default 9

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

本文标签: