1 回答

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個贊
問這個問題幫助我回答了我自己的問題,或者找到了解決方案。下面的所有內(nèi)容都使用在請求之外運(yùn)行的線程進(jìn)行了測試。
原來我們可以通過 API 注入服務(wù)提供者來創(chuàng)建我們自己的實(shí)例!
ReadOnly IServiceProvider _ServiceProvider;
MySingulation(IServiceProvider serviceProvider)
{
_ServiceProvider = serviceProvider;
}
一旦我們通過注入獲得了 IServiceProvider 的句柄,我們就可以使用 MVC 核心 API 來創(chuàng)建上下文實(shí)例
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
// ...
}
現(xiàn)在,重要的是要記住我們首先在 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 關(guān)注
- 90 瀏覽
添加回答
舉報