Dependency injection: How to pass the injection container around?

前端 未结 2 992
醉酒成梦
醉酒成梦 2020-12-31 21:35

(This question does not rely on a specific IoC framework, so the interfaces and types in my samples are meta-types. Just replace them with the appropriate types for your fav

相关标签:
2条回答
  • 2020-12-31 21:54

    You shouldn't pass the container around.

    Instead, your entry-point/main method asks the container for the objects it needs to get started - such as your App object/bean. The container then returns the full object graph connected to App, which allows you to run app.Run(), with all the dependencies satisfied.

    It's a bit of an anti-pattern for the objects to be aware of the container, or for each object to be asking the container for it's dependencies - if you do this then you have not inverted control and what you have is not dependency injection - you still have objects asking for what they need, rather than being given what they need.

    0 讨论(0)
  • 2020-12-31 22:08

    It's best to avoid injecting the injector. Just create the types you need, and then start executing. I've written a somewhat longer post on this topic: Accessing the DI container

    0 讨论(0)
提交回复
热议问题