已解决的对象与其容器具有相同的生命周期/处置周期,除非您使用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)
方法之外是不可用的,除非你做了一些时髦的事情让它可以在外面访问(你不应该这样做)。
当然,它鼓励尽快释放临时服务,特别是如果他们消耗大量资源。