How to free resources and dispose injected service in ASP.NET 5/Core by the end of request?

你。 提交于 2020-01-09 10:01:52

问题


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?


回答1:


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.

Edit(13.06.2017): They mention in official documents now. Disposing of services




回答2:


When using AddScoped is by design that the object will have it's lifetime associated with the Request.




回答3:


I see no one mentioned this yet, but besides implementing IDisposable in your type, you can also use {HttpContext}.Response.RegisterForDispose(objectToDispose). Typically this is used to register an object at the start of a request (such as a controller action) to be disposed when the request ends.



来源:https://stackoverflow.com/questions/35872163/how-to-free-resources-and-dispose-injected-service-in-asp-net-5-core-by-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!