Best Practice for Using a Dependency Injection / Service Locator Container?

TLDR: What is the best way to use an IoC container once you have it configured?


I've been reading up on IoC (Dependency Injection, Service Locators, etc.). I get DI is good and that IoC containers can make it easier to instantiate objects, but what I have not found is anything that shows how to actually use the injection container once you have it configured. Most tutorials stop at just getting the container setup and send you on your way, but for some reason it's just not clicking as to how to best utilize your injection container once it's configured.

From what I can tell there are 2 ways I could use a container:

  • Instantiate every conceivable dependency up front and have those flow through the application via a single entry point with a potentially massive number of dependencies.
  • This seems silly because you may be creating lots of class instances you don't really need. It also seems that you would hardly need a container to do this.
  • Move the injection container to some global scope and call it whenever I need a new object that has dependencies.
  • This seems silly because a.) now you created a global/singleton (barf) and b.) now your dependency injector iteself is a dependency.
  • Both of these options don't seem ideal, so I'm wondering if I'm just missing something fundamental about how an injection container is intended to be used in practice. Any help would be appreciated!


    You are looking for the concept of object lifetimes. Autofac has a great primer on the subject.

    链接地址: http://www.djcxy.com/p/77716.html

    上一篇: C ++:奇怪的是“私人”的错误

    下一篇: 使用依赖注入/服务定位器容器的最佳实践?