I'm implementing dependency injection in my project. I've come across two ways to add a singleton service -
services.AddSingleton(new MyCustomService())
and
services.AddSingleton<MyCustomService>()
Both methods seem to work. What's the difference between these two methods, and which one should I be using?
When using the generic .AddSingleton<TService>() method (and .AddSingleton<TService, TImplementation>(), the type is created, controlled, and disposed of by the container. When the constructor contains other dependencies, those dependencies are automatically injected (a technique called "Auto-Wiring").
Instances supplied using .AddSingleton<TService>(TService) already exist. In that case, the container will not dispose of that instance when it implements IDisposable or IAsyncDisposable. You are responsible for disposing of that instance yourself.
Since .AddSingleton<TService>(TService) is supplied with an already existing instance, the container can't inject any dependencies, because in order to do that, it must also create the instance.
When instances are registered using the .AddSingleton<TService>(Func<TService>) method, the Func<TService> delegate is in control over the creation of the dependency, but the instance returned by the delegate will still be tracked and disposed by the container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With