How should I inject (using .NET Core's built-in dependency injection library, MS.DI) a DbContext
instance into a Singleton? In my specific case the singleton is an IHostedService
?
What have I tried
I currently have my IHostedService
class take a MainContext
(deriving from DbContext
) instance in the constructor.
When I run the application I get:
Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.
So I tried to make the DbContextOptions
transient by specifying:
services.AddDbContext<MainContext>(options =>
options.UseSqlite("Data Source=development.db"),
ServiceLifetime.Transient);
in my Startup
class.
But the error remains the same, even though, according to this solved Github issue the DbContextOptions
passed should have the same lifetime specified in the AddDbContext
call.
I can't make the database context a singleton otherwise concurrent calls to it would yield concurrency exceptions (due to the fact that the database context is not guaranteed to be thread safe).