1 回答

TA貢獻1834條經(jīng)驗 獲得超8個贊
您可以在您的方法中創(chuàng)建一個范圍,但首先您必須將 IServiceScopeFactory 注入您的類。
using Microsoft.Extensions.DependencyInjection;
public class SomeService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
public SomeService(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
public Task DoStuff()
{
using (var serviceScope = _serviceScopeFactory.CreateScope())
{
var unitOfWork = serviceScope.ServiceProvider.GetRequiredService<UnitOfWork>();
}
}
}
請記住,您創(chuàng)建的對象將在您釋放作用域時被釋放。另外,如果你不處理范圍,你會得到內(nèi)存泄漏
- 1 回答
- 0 關(guān)注
- 181 瀏覽
添加回答
舉報