如何在方法期间使用依赖注入从池中获取 DbContext 的实例?

我想在使用范围期间在池中的函数中使用 DbContext


我已经尝试将 IServiceProvider 添加到工厂并让工厂解析上下文并将其放入 UoW 但随后它告诉我在其他线程中使用了相同的包含。


services.AddDbContextPool<EmployeeContext>(options => options.UseSqlServer(connection));

...

using (var unitOfWork = factory.CreateUnitOfWork())

{

}

我想在使用依赖注入的 DbContextPool 的函数内创建一个工作单元范围。


潇潇雨雨
浏览 146回答 1
1回答

MMMHUHU

您可以在您的方法中创建一个范围,但首先您必须将 IServiceScopeFactory 注入您的类。using Microsoft.Extensions.DependencyInjection;public class SomeService{&nbsp; &nbsp; private readonly IServiceScopeFactory _serviceScopeFactory;&nbsp; &nbsp; public SomeService(IServiceScopeFactory serviceScopeFactory)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _serviceScopeFactory = serviceScopeFactory;&nbsp; &nbsp; }&nbsp; &nbsp; public Task DoStuff()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; using (var serviceScope = _serviceScopeFactory.CreateScope())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var unitOfWork =&nbsp; serviceScope.ServiceProvider.GetRequiredService<UnitOfWork>();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}请记住,您创建的对象将在您释放作用域时被释放。另外,如果你不处理范围,你会得到内存泄漏
打开App,查看更多内容
随时随地看视频慕课网APP