.net-coresingletondbcontext

How to use DbContext in singleton service


I have a background service.

In its ExecuteAsync method I have this code:

var configuration = scope.ServiceProvider.GetService<IConfiguration>();
var db = scope.ServiceProvider.GetRequiredService<MyDbContext>();

How can I specify connection string to db? When I use it in a scoped service, I can just do:

services
    .AddDbContext<MyDbContext>(options =>
        {              
          options.UseSqlServer(builder.Configuration.GetConnectionString("ConnStringInfo"));
        })

But I cannot do this when the host is a singleton service.

How can I do it for a singleton?


Solution

  • According to the Microsoft documentation, you can try to update your code for the below, it should work

    https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/#the-dbcontext-lifetime

    services
    .AddDbContext<MyDbContext>(options =>
    {
        options.UseSqlServer(builder.Configuration.GetConnectionString("ConnStringInfo"));
    }, ServiceLifetime.Transient, ServiceLifetime.Singleton);