ASP.NET 5/Core 如何在请求结束前释放资源并处理注入的服务? [英] How to free resources and dispose injected service in ASP.NET 5/Core by the end of request?
问题描述
我有一个服务,它使用 ASP.NET Core 的默认依赖注入容器注入到控制器中:
I have a service which is injected into a controller using the ASP.NET Core's default Dependency Injection Container:
public class FooBarService : IDisposable {
public void Dispose() { ... }
}
services.AddScoped<FooBarService>();
这会为每个请求创建一个实例.如何确保框架在每次请求结束时处理 FooBarService 实例,而不依赖于析构函数和垃圾收集?
This creates one instance per request. How to ensure that the framework would dispose the FooBarService instance by the end of each request, without relying on destructors and garbage collection?
推荐答案
与所有其他 DI 容器一样,它会在尊重实例生命周期的情况下为您处理 IDisposable 实例.
Like the all other DI containers, it will dispose IDisposable instances for you with respecting life time of instance.
在您的情况下,如果实例注册为 Scoped
(每个请求的实例).请求完成后会处理这个实例.
In your stuation, if instance is registered as Scoped
(Instance Per Request). It will dispose this instance after request is completed.
编辑:在官方文件中,他们没有提到这一点.因此,让我们检查源代码以确保:
Edit: In official documents they don't mention this. So Let's check source code to be sure:
在创建范围时,ServiceScopeFactory 返回一个新的 ServiceScope 依赖于 relrollow"服务提供商和一次性使用.
When a scope is created, ServiceScopeFactory returns a new ServiceScope which is depended with ServiceProvider and disposable.
ServiceProvider
有 private List
当 TransientCallSite
在 CaptureDisposable
方法中被 invoke
d 时,它保持一次性服务.另外 ServiceProvider
有 private readonly Dictionary
保留 Scoped
的所有服务.
ServiceProvider
has private List<IDisposable> _transientDisposables;
which keeps disposable services when TransientCallSite
is invoke
d in CaptureDisposable
method. Also ServiceProvider
has private readonly Dictionary<IService, object> _resolvedServices = new Dictionary<IService, object>();
which keeps all services for Scoped
.
当liftime/scope 结束时,ServiceScope
被释放.然后它处理 ServiceProvider
处理所有 _transientDisposables
然后它检查 _resolvedServices
并在 ServiceProvider
的字典中处理一次性服务.
When liftime/scope finishes, the ServiceScope
is disposed. Then it disposes ServiceProvider
which disposes all _transientDisposables
and then it checks _resolvedServices
and disposes disposable services in the dictionary in ServiceProvider
.
编辑(13.06.2017):他们现在在官方文件中提到.服务生命周期一个>
Edit(13.06.2017): They mention in official documents now. Service Lifetimes
这篇关于ASP.NET 5/Core 如何在请求结束前释放资源并处理注入的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!