开发者

When to use an IOC container?

开发者 https://www.devze.com 2022-12-25 09:01 出处:网络
I\'m 开发者_如何学Pythontrying 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 implemen

I'm 开发者_如何学Pythontrying 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 implementations for each interface, I would lean towards just handling that myself.

If I have a small application that uses 2-3 interfaces and each interface has 2-3 concrete implementations, should I use a full-blown container? Would something something simple like this suffice?

Basically I'm trying to understand when it's appropriate to manually handle these dependencies, when (or if) I should use something simple like the above, and when to use an IOC container like Ninject, Windsor, etc.... It might not be appropriate to put a number on something like this, but how can I tell it's time to use an IOC container?


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

精彩评论

暂无评论...
验证码 换一张
取 消