何时使用IOC容器? [英] When to use an IOC container?

查看:76
本文介绍了何时使用IOC容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解何时应该使用容器而不是手动注入依赖项。如果我有一个使用1-2个接口的应用程序,并且每个接口只有1-2个具体实现,则我倾向于自己处理。

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 implementations for each interface, I would lean towards just handling that myself.

如果我有一个使用2-3个接口的小型应用程序,并且每个接口都有2-3个具体的实现,我应该使用成熟的容器吗?会像就足够了吗?

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?

基本上,我试图了解何时手动处理这些依赖项是合适的,何时(或是否)应该使用像上面这样简单的东西,以及何时使用IOC容器(例如Ninject,Windsor等)。在这样的东西上放置数字可能不合适,但是我怎么知道是时候使用IOC容器了?

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?

推荐答案

在这里要意识到的重要一点是,您可以(并且应该)在 DI友好,但与容器无关的方式

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.

如果以此方式设计应用程序,则选择的DI容器(或不使用DI容器)只围绕一个

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.

如果您只有很少的依赖项,则可以选择使用穷人的DI ,或者您可以选择使用功能强大的 DI容器。以这种方式使用,您将不会依赖任何特定的DI容器,因此在可维护性方面,选择变得不那么重要

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容器可帮助您管理复杂性,包括对象寿命。按此处所述使用,它不会做任何您无法手写的事情,但是会做到更好,更简洁。这样,我何时开始使用DI容器的门槛将非常低。

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.

一旦我摆脱了一些依赖,我将开始使用DI容器。 无论如何,其中大多数都很容易上手

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.

更新:我的 2012年11月对该问题的回答

这篇关于何时使用IOC容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆