1 回答

TA贡献1878条经验 获得超4个赞
问这个问题帮助我回答了我自己的问题,或者找到了解决方案。下面的所有内容都使用在请求之外运行的线程进行了测试。
原来我们可以通过 API 注入服务提供者来创建我们自己的实例!
ReadOnly IServiceProvider _ServiceProvider;
MySingulation(IServiceProvider serviceProvider)
{
_ServiceProvider = serviceProvider;
}
一旦我们通过注入获得了 IServiceProvider 的句柄,我们就可以使用 MVC 核心 API 来创建上下文实例
using(var serviceScope = _ServiceProvider.CreateScope())
{
// Don't get confused -- Call GetService from the serviceScope and
// not directly from the member variable _ServiceProvider.
var context = serviceScope.ServiceProvider.GetService<YourAppDbContext>();
// ...
// Make use of the dbcontext
// ...
}
现在,重要的是要记住我们首先在 Startup.cs 中使用了 MVC 核心池。
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddDbContextPool<YourAppDbContext>(options => {
options.UseSqlServer(settings.Connection);
});
// Oh, it's important the singultion was created within Core's LifeCycle/API
services.AddSingleton<MySingulation>();
//...
}
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报