何时释放.NETCore 依赖项注入的实例?

NET Core 在 IServiceCollection上使用扩展方法来建立依赖注入,然后当需要一个类型时,它使用适当的方法来创建一个新的实例:

  • AddTransient<T>-添加每次请求时再次创建的类型。
  • AddScoped<T>-添加为请求范围保留的类型。
  • AddSingleton<T>-在第一次请求时添加一个类型,并保留它。

我有实现 IDisposable的类型,如果没有处理它们,就会导致问题-在每种模式中,什么时候实际调用 Dispose

是否需要添加任何内容(例如异常处理)以确保总是释放实例?

34911 次浏览

The resolved objects have the same life-time/dispose cycle as their container, that's unless you manually dispose the transient services in code using using statement or .Dispose() method.

In ASP.NET Core you get a scoped container that's instantiated per request and gets disposed at the end of the request. At this time, scoped and transient dependencies that were created by this container will get disposed too (that's if they implement IDisposable interface), which you can also see on the source code 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();
}
}

Singletons get disposed when the parent container gets disposed, usually means when the application shuts down.

TL;DR: As long as you don't instantiate scoped/transient services during application startup (using app.ApplicationServices.GetService<T>()) and your services correctly implement Disposable interface (like pointed in MSDN) there is nothing you need to take care of.

The parent container is unavailable outside of Configure(IApplicationBuilder app) method unless you do some funky things to make it accessible outside (which you shouldn't anyways).

Of course, its encouraged to free up transient services as soon as possible, especially if they consume much resources.