When to use an IOC container?

前端 未结 1 1784
無奈伤痛
無奈伤痛 2021-02-04 04:59

I\'m trying to understand when I should use a container versus manually injecting dependencies. If I have an application that uses a 1-2 interfaces and only has 1-2 concrete im

相关标签:
1条回答
  • 2021-02-04 05:42

    The important thing to realize here is that you can (and should) write your code in a DI-friendly, but container-agnostic manner.

    This means that you should always push the composition of dependencies to a point where you can't possibly defer it any longer. This is called the Composition Root and is often placed in near the application's entry point.

    If you design your application in this way, your choice of DI Container (or no DI Container) revolves around a single place in your application, and you can quickly change strategy.

    You can choose to use Poor Man's DI if you only have a few dependencies, or you can choose to use a full-blown DI Container. Used in this fashion, you will have no dependency on any particular DI Container, so the choice becomes less crucial in terms of maintainability.

    A DI Container helps you manage complextity, including object lifetime. Used like described here, it doesn't do anything you couldn't write in hand, but it does it better and more succinctly. As such, my threshold for when to start using a DI Container would be pretty low.

    I would start using a DI Container once I get past a few dependencies. Most of them are pretty easy to get started with anyway.


    Update: My November 2012 answer to that question.

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