简体   繁体   中英

Is dependency injection container a singleton?

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!

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:

  1. It's convenient
  2. efficient
  3. easy to read and understand
  4. makes it difficult to use it the wrong way
  5. Allows it to be easily used as a static object

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