I have a problem when try to use database context in one Singleton Service in my app.
App.cs
...
var service = builder.Services;
service.AddDbContext<MyDBContext>(options => options.UseSqlite(connectionString));
service.AddSingleton<MyMonitorManager>();
...
MyDBContext.cs
public class MyDBContext : ApiAuthorizationDbContext<ApplicationUser>
{
public DroneDBContext(...): base(options, operationalStoreOptions){}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){}
protected override void OnModelCreating(ModelBuilder modelBuilder){}
}
MyMonitorManager.cs
public class MyMonitorManager {
private readonly MyDBContext _databaseManager;
...
}
There are errors:
Cannot consume scoped service 'MyController.MyDBContext' from singleton 'MyController.Service.MyMonitorManager'.
I try to search here and think about use like this:
MyDBContext dbContext = new MyDBContext();
service.AddSingleton(new MyMonitorManager(dbContext));
But not sure this is how I should do in .NET 6