`
javatoyou
  • 浏览: 1013261 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

IoC and Castle.IoC

 
阅读更多

1. 什么是 IoC ?

关于IoC的详细解释请看 Inversion of Control Containers and the Dependency Injection pattern (英文/中文),本文只会作一些简单介绍

IoC(Inversion of Control),我们叫它"控制反转",也可以叫它"依赖注入"(Dependency Injection)。

引用自 JGTM'2004 [MVP] 的话来解释IoC
>>> 原来我是这样解释应用IoC的意图和方式的(但还是不够清晰):如果我想打破A->B的依赖,那么我可以通过引入A、B之间的交互协议I来办到,也 就是将A->B变为(A->I)+(I<-B)(此举同时满足了DIP和OCP原则),那么IoC就是帮助我们用各种各样的方法(如构 造器注入、属性注入或接口注入等等)在运行期把I的一个具体实现B传达给A使用的一系列机制。

使用IoC的主要目地就是实现程序模块的低偶合,在DotNet下比较著名的IoC框架是Castle和Spring.net。


2. IoC的三种形式

依赖注入的形式主要有三种,我分别将它们叫做构造子注入(Constructor Injection)、设值方法注入(Setter Injection)和接口注入(Interface Injection)。


3. Castle中的IoC介绍

Castle.IoC 支持构造子注入和设值方法注入,但更侧重构造子注入。


4. 使用Castle.IoC

使用 Castle.IoC 主要是配置 components

4.1 使用代码配置

publicstaticWindsorContainercontainer=newWindsorContainer(@"../../config.xml");
container.AddComponent(
"FormatService",typeof(FormatService));
container.AddComponent(
"format",typeof(IMessageFormat),typeof(HtmlMessage));

4.2 使用XML文件配置
<?xmlversion="1.0"encoding="utf-8"?>
<castle>
<components>
<componentid="FormatService"
type
="IoCSample.FormatService,IoCSample"/>

<componentid="format"
service
="IoCSample.Components.IMessageFormat,IoCSample"
type
="IoCSample.Components.HtmlMessage,IoCSample"/>
</components>
</castle>


如何配置IList,IDictionary,Array等复杂类型

IDictionary
代码:
publicclassC
{
publicC(){}
publicC(IDictionaryd)
{
this.dictionary=d;
}

privateIDictionarydictionary;
publicIDictionaryDictionary
{
get{returnthis.dictionary;}
}

}
配置:
<componentid="c"type="CastleDemo.C,CastleDemo">
<parameters>
<d>
<itemkeyType="System.String"valueType="System.String">
<itemkey="a">a</item>
<itemkey="b">b</item>
</item>
</d>
</parameters>
</component>


IList
代码:
publicclassD
{
privateIListlist;
publicD(){}
publicIListList
{
get{returnthis.list;}
}

publicD(IListlist)
{
this.list=list;
}

}
配置:
<componentid="d"type="CastleDemo.D,CastleDemo">
<parameters>
<list>
<itemtype="System.String">
<item>a</item>
<item>b</item>
<item>c</item>
</item>
</list>
</parameters>
</component>


Array
代码:
publicclassE
{
privateint[]ages;
publicint[]Ages
{
get{returnthis.ages;}
}

publicE()
{

}

publicE(int[]ages)
{
this.ages=ages;
}

}
配置:
<componentid="e"type="CastleDemo.E,CastleDemo">
<parameters>
<ages>
<itemtype="System.Int32">
<item>1</item>
<item>2</item>
<item>3</item>
</item>
</ages>
</parameters>
</component>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics