IoC and Castle.IoC

本文介绍了IoC(控制反转)的概念及其主要目的——实现程序模块的低耦合。详细阐述了依赖注入的三种形式,并以Castle.IoC为例展示了如何通过代码和XML配置进行依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 >
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值