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 使用代码配置
public
static
WindsorContainercontainer
=
new
WindsorContainer(
@"
../../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
>
<
component
id
="FormatService"
type
="IoCSample.FormatService,IoCSample"
/>

<
component
id
="format"
service
="IoCSample.Components.IMessageFormat,IoCSample"
type
="IoCSample.Components.HtmlMessage,IoCSample"
/>
</
components
>
</
castle
>
如何配置IList,IDictionary,Array等复杂类型
IDictionary
代码:
public
class
C

{

publicC()
{}
publicC(IDictionaryd)


{
this.dictionary=d;
}
privateIDictionarydictionary;
publicIDictionaryDictionary


{

get
{returnthis.dictionary;}
}
}
配置:
<
component
id
="c"
type
="CastleDemo.C,CastleDemo"
>
<
parameters
>
<
d
>
<
item
keyType
="System.String"
valueType
="System.String"
>
<
item
key
="a"
>
a
</
item
>
<
item
key
="b"
>
b
</
item
>
</
item
>
</
d
>
</
parameters
>
</
component
>
IList
代码:
public
class
D

{
privateIListlist;

publicD()
{}
publicIListList


{

get
{returnthis.list;}
}
publicD(IListlist)


{
this.list=list;
}
}
配置:
<
component
id
="d"
type
="CastleDemo.D,CastleDemo"
>
<
parameters
>
<
list
>
<
item
type
="System.String"
>
<
item
>
a
</
item
>
<
item
>
b
</
item
>
<
item
>
c
</
item
>
</
item
>
</
list
>
</
parameters
>
</
component
>
Array
代码:
public
class
E

{
privateint[]ages;
publicint[]Ages


{

get
{returnthis.ages;}
}
publicE()


{

}
publicE(int[]ages)


{
this.ages=ages;
}
}
配置:
<
component
id
="e"
type
="CastleDemo.E,CastleDemo"
>
<
parameters
>
<
ages
>
<
item
type
="System.Int32"
>
<
item
>
1
</
item
>
<
item
>
2
</
item
>
<
item
>
3
</
item
>
</
item
>
</
ages
>
</
parameters
>
</
component
>