gpt4 book ai didi

c# - .NET Core 6 将数据库上下文注入(inject)单例服务

转载 作者:行者123 更新时间:2023-12-01 22:54:27 25 4
gpt4 key购买 nike

当我尝试在我的应用程序的一个单例服务中使用数据库上下文时遇到问题。

应用.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;
...
}

有错误:

Cannot consume scoped service 'MyController.MyDBContext' from singleton 'MyController.Service.MyMonitorManager'.

我尝试在这里搜索并考虑这样使用:

MyDBContext dbContext = new MyDBContext();
service.AddSingleton(new MyMonitorManager(dbContext));

但不确定在 .NET 6 中我应该怎么做

最佳答案

您可以在单例类中使用 IServiceScopeFactory 来创建新范围,然后从中获取数据库上下文引用:

public class MyMonitorManager {
private readonly IServiceScopeFactory _scopeFactory;

public MyMonitorManager(IServiceScopeFactory _scopeFactory)
{
_scopeFactory = scopeFactory;
}

public SomeMethod()
{
using (var scope = _scopeFactory.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<MyDBContext>();
...
}
}
}

关于c# - .NET Core 6 将数据库上下文注入(inject)单例服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73618839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com