Reputation: 15091
I am learning DI in .Net Core and I find all examples only use one instance of ServiceCollection
. I wonder whether this instance must be a singleton but I get confused because we can invoke new
. Probably because of my lack of knowledge, it really makes sense to have multiple instances of ServiceCollection
. Any comment and suggestion are welcome!
Upvotes: 0
Views: 942
Reputation: 1129
It's both more efficient
and less Dangerous
than creating multiple service providers. Creating one instance allows you to have all your services in one place instead of divided over multiple provider instances.
A service provider doesn't have to be a singleton, but it makes users of dependency injection frameworks less likely go down the bad road.
The bad road in this case is separating your dependencies
and later having to pass/ know the right dependency provider
to choose from when getting your dependencies.
This makes your code more complicated than it has to be, as well as creating no benefit for both you and especially other people who will join you on your project and have to figure out which provider had the object which can access the database.
Most frameworks
have their service providers
accessible statically which also allows you to retrieve services and merge the service provider into your project far easier. Having multiple instances would make this difficult.
Normally with dependency injection you would for example pass it directly in your constructor.
So in short:
Upvotes: 2