Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. Service Lifetimes


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...