简体   繁体   中英

How to dipose helper disposables using DI in ASP.NET core?

For regular case how to manage disposables such post as How to correctly and safely dispose of singletons instances registered in the container when an ASP.NET Core app shuts down explains how to do it.

But I have a slightly different case -- I don't have single instance of some worker IFoo like here:

interface IFoo : IDisposable // not my case

which you know how to dispose, just call Dispose on an instance of IFoo .

No, my IFoo is not IDisposable :

interface IFoo // my case

instead of single instance, I have a pair of instances on creation -- (IFoo,IDisposable) . When I have to do real work, I use the first item, because there is all logic there, when I am done, I call Dispose on the second item.

You could say it is decoupling put at extreme.

And when I am at ASP.NET Core I have problem with DI -- I have a pair like above, I can register IFoo with for example services.AddScoped , but how to tell services that there is distinct/separate IDisposable at hand which should be disposed when the work is done and the scope is gone?

You could create a wrapper around (IFoo, IDisposable) , let's say:

public class DisposableFoo : IDisposable
{
    // Assume FooConcrete implements IFoo and IDisposable
    private readonly FooConcrete _foo;

    public DisposableFoo(FooConcrete fooConcrete) { _foo = fooConcrete; }

    public IFoo Instance => _foo;

    public void Dispose() => _foo.Dispose();
}

And then in Startup.cs you could do the following to keep your abstractions clean:

services.AddTransient<FooConcrete>();
services.AddScoped<DisposableFoo>();
services.AddScoped<IFoo>(ctx => ctx.Resolve<DisposableFoo>.Instance); 

In this case the underlying FooConrecte will be disposed at the end of scope lifetime properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM