Factory Func Implementation with ASP.NET Core DI

I am trying to do something like this:

public class FooService : IFooService {
    public FooService(Func<IBarService> barFactory) { ... }
}
public class BarService : IBarService, IDisposable { ... }

services.AddSingleton<IFooService, FooService>();
services.AddTransient<IBarService, BarService>();
services.AddSingleton<Func<IBarService>>(ctx => () => ctx.GetService<IBarService());

      

This works with the resolution of the instance BarService

, but I can't figure out how to properly manage its lifetime. When I do this inside one of the members FooService

:

using (var bar = _barFactory())
{
    ...
}

      

I am getting ObjectDispoedException

:

System.ObjectDisposedException: Unable to access the remote object. A common cause of this error is to remove the context that was resolved from dependency injection and then try to use the same context instance elsewhere in your application. This can happen if you call Dispose () in the context, or if you wrap the context in a using statement. If you are using dependency injection, you must let the dependency injection container take care of disposing of the context instances.

However, if I just do var bar = _barFactory();

, without a using statement, I have no way to tell the DI container that I am done with an instance and it can be removed.

What's the correct approach here?


(Side note: yes, I know some would argue that a singleton service should not depend on a transient service. This is not what is happening here: the singleton service depends on a singleton factory that creates temporary instances. The singleton then uses the transient service to one or two operators and then executed on it, so there shouldn't be any real life span issues here.)

+3


source to share


1 answer


As described in the documentation :

The container will call Dispose

for the types IDisposable

it creates. However, if you add an instance to the container yourself, it will not be removed.



So just don't use the instruction using

and you should be fine.

+2


source







All Articles