I have a service which was created not by me, but I need to provide it via DI (with other my services). So, my DI must to not dispose this service when DI scope (or DI container) will be disposed.
For Autofac I can prevent disposing particular service (instead of all):
builder.RegisterType<SomeComponent>().ExternallyOwned();
Is it possible to do the same for ServiceCollection by Microsoft?
I have a service which was created not by me, but I need to provide it via DI (with other my services). So, my DI must to not dispose this service when DI scope (or DI container) will be disposed.
For Autofac I can prevent disposing particular service (instead of all):
builder.RegisterType<SomeComponent>().ExternallyOwned();
Is it possible to do the same for ServiceCollection by Microsoft?
Share Improve this question edited Jan 18 at 22:40 Andrey Bushman asked Jan 18 at 21:28 Andrey BushmanAndrey Bushman 12.5k23 gold badges102 silver badges210 bronze badges 17 | Show 12 more comments1 Answer
Reset to default 2Microsoft DI disposes the services created (or you can call it "owned") by it automatically. From the docs:
The container is responsible for cleanup of types it creates, and calls
Dispose
onIDisposable
instances. Services resolved from the container should never be disposed by the developer. If a type or factory is registered as a singleton, the container disposes the singleton automatically.
There are several options to consider:
You can use singletons with provided instance. This is mentioned in the
Services not created by the service container
section of the docs:// Register example service in IServiceCollection builder.Services.AddSingleton(new ExampleService());
In the preceding code:
- The ExampleService instance is not created by the service container.
- The framework does not dispose of the services automatically.
- The developer is responsible for disposing the services.
Though this will only work if you need a single instance per app lifetime.
Replace the default container with a 3rd party one (already mentioned Autofac for example) - see Default service container replacement.
Use the factory pattern - register a factory providing an instance of the registered class. Basically it is what EF Core does with
DbContext
factory - the factory is registered in the container but the created resource is not and should explicitly be disposed by the developer.
IDisposable
and holds a reference to the original service? That way the proxy/adapter can be used and thrown away without disposing the original service. – Progman Commented Jan 18 at 22:28