IOC容器的例子 [英] Examples of IoC Containers

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

问题描述

有没有人有IoC容器中,如何,为什么使用它们很好的例子(pferably $ P $在C#)和和?我已签了维基页面和<一个href=\"http://ayende.com/Blog/archive/2007/10/20/Building-an-IoC-container-in-15-lines-of-$c$c.aspx\">Ayende's举例来说,但我不完全得到的概念呢。

Does anyone have good examples of IoC containers (preferably in c#) and how and why to use them ? I have checked out the wiki page and Ayende's example, but I don't quite get the concept yet.

和何时何地我应该使用IoC容器?

And when and where should I use an IoC container ?

推荐答案

我用结构地图颇有几分。你的问题的其余部分是pretty加载。我会试着解释一个例子的概念。

I've used structure map quite a bit. The rest of your question is pretty loaded. I'll try to explain the concept in an example.

假设你创建了一个网站,将通过PayPal接受付款。贝宝现在是一个依赖。但是,你不想对一个特定的贝宝提供code。

Suppose you created a website that will accept payments through PayPal. PayPal is now a dependency. But you don't want to code against a specific PayPal provider.

相反,你会反对这样的界面创建和code ..

Instead You would create and code against an interface like this..

interface IPaymentProcessor
{
      bool ProcessPayment(amount, ....);
}

所有你的PayPal code将驻留在您实现接口的方法的类。 PayPalPaymentProcessor ​​例如:

All your paypal code would reside in a class that implements the methods of your interface. PayPalPaymentProcessor for example

现在你有一个对象,你将实际使用来处理付款。这可能是一个控制器(asp.net-MVC中,视图模型 - WPF),或只是一个类,如下所示。

Now you have an object that you will actually use to process the payments. This could be a Controller(asp.net-mvc, ViewModel-wpf) or just a class as shown here.

class PaymentProcessor
{
    private IPaymentProcessor _processor = null;
    public PaymentProcessor(IPaymentProcessor processor)
    {
        _processor = processor;
    }

    public bool ProcessTransaction(Transaction trans)
    {
       _processor.ProcessPayment(trans.amount, ...);
    }
}

这是一个IoC进来,而是你手动调用构造函数,你会让一个IoC的注入的依赖。

PaymentProcessor processor = ObjectFactory.GetInstance<PaymentProcessor>();

这件code的结构讲述图任何时候你看到需要一个构造函数
IPaymentProcessor,返回一个新PayPalPaymentProcessor。

This piece of code tells structure map "Anytime you see a constructor that needs an IPaymentProcessor, return a new PayPalPaymentProcessor".

ObjectFactory.Initialize(x =>
{ 
 x.ForRequestedType<IPaymentProcessor>().TheDefaultIsConcreteType<PayPalPaymentProcessor>();
});

所有这些映射是从您的实现code分离,你可以在所需要的小重构稍后换出这些。还有很多更多的国际石油公司,但是这是一个基本的概念。您可以自动构造的注入,直接避免调用的ObjectFactory为好。

All this mapping is separate from your implementation code and you could swap out these at a later point with little refactoring needed. There is a lot more to IoCs, but that is a basic concept. You can automate the injection of constructors to avoid the calls directly to ObjectFactory as well.

希望这有助于!

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

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