在ASP.NET 5 / Core中如何释放资源并处理注册服务? [英] How to free resources and dispose injected service in ASP.NET 5/Core by the end of request?

查看:112
本文介绍了在ASP.NET 5 / Core中如何释放资源并处理注册服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用ASP.NET Core的默认依赖注入容器注入到控制器中的服务:

  public class FooBarService:IDisposable {
public void Dispose(){...}
}

services.AddScoped< FooBarService>();

每个请求创建一个实例。如何确保框架在每个请求结束之前处理FooBarService实例,而不依赖析构函数和垃圾回收?

解决方案

像所有其他DI容器一样,它将为您保留IDisposable实例,以保持实例的使用寿命。



在您的判断中,如果实例注册为 Scoped (每个请求的实例)。它将在请求完成后处理此实例。



修改
在官方文档中,他们没有提到这一点。
所以我们来检查一下源代码:



创建范围时, ServiceScopeFactory 返回一个新的 ServiceScope ,它取决于 ServiceProvider 和一次性。



ServiceProvider 私人列表< IDisposable> _transientDisposables; TransientCallSite 中保留一次性服务 d > CaptureDisposable 方法。另外 ServiceProvider 私有只读字典< IService,object> _resolvedServices =新词典< IService,object>(); 保留所有服务 Scoped



当升级/范围完成时,将处理 ServiceScope 。然后它处理 ServiceProvider ,它处理所有的 _transientDisposables ,然后检查 _resolvedServices 并在 ServiceProvider 中的字典中配置一次性服务。


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>();

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?

解决方案

Like the all other DI containers, it will dispose IDisposable instances for you with respecting life time of instance.

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:

When a scope is created, ServiceScopeFactory returns a new ServiceScope which is depended with ServiceProvider and disposable.

ServiceProvider has private List<IDisposable> _transientDisposables; which keeps disposable services when TransientCallSite is invoked in CaptureDisposable method. Also ServiceProvider has private readonly Dictionary<IService, object> _resolvedServices = new Dictionary<IService, object>(); which keeps all services for Scoped.

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.

这篇关于在ASP.NET 5 / Core中如何释放资源并处理注册服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆