已解決的對象與其容器具有相同的生命週期/處置週期,除非您使用using
語句或.Dispose()
方法手動處理代碼中的瞬態服務。
在ASP.NET Core中,您將獲得一個作用域容器,該容器根據請求進行實例化,並在請求結束時處理。此時,由該容器創建的作用域和臨時依賴關係也將被處置(即如果它們實現了IDisposable
接口),您也可以在源代碼here上看到該依賴關係。當父容器被布置
public void Dispose()
{
lock (ResolvedServices)
{
if (_disposeCalled)
{
return;
}
_disposeCalled = true;
if (_transientDisposables != null)
{
foreach (var disposable in _transientDisposables)
{
disposable.Dispose();
}
_transientDisposables.Clear();
}
// PERF: We've enumerating the dictionary so that we don't allocate to enumerate.
// .Values allocates a ValueCollection on the heap, enumerating the dictionary allocates
// a struct enumerator
foreach (var entry in ResolvedServices)
{
(entry.Value as IDisposable)?.Dispose();
}
ResolvedServices.Clear();
}
}
單身得到安置,當應用程序關閉通常意味着。
TL; DR:在應用程序啓動,只要你不要實例作用域/短暫性服務(使用app.ApplicationServices.GetService<T>()
)和您的服務正確地實現一次性接口(如pointed in MSDN)沒有什麼,你需要照顧。
父容器在Configure(IApplicationBuilder app)
方法之外是不可用的,除非你做了一些時髦的事情讓它可以在外面訪問(你不應該這樣做)。
當然,它鼓勵儘快釋放臨時服務,特別是如果他們消耗大量資源。