依赖注入容器之Castle Windsor
一.Windsor的使用
Windsor的作为依赖注入的容器的一种,使用起来比较方便,我们直接在Nuget中添加Castle Windsor,将会自动引入Castle.Core 和 Castle.Windsor,就可以正常使用。
1.逐个组件进行注册
使用注册模块中的Component
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<IAppleService>() //接口
.ImplementedBy<AppleService>());
在这里取一个特殊的例子,我们注册一个带有参数的的实例,我们直接使用Resolve实现兑现的注入
public class AppleService : IAppleService
{
public AppleService(decimal price)
{
this.Price = price;
}
public decimal Price { get; set ; }
public void Output()
{
Console.WriteLine(Price);
}
}
//具体的实现注入
var apple= container.Resolve<IAppleService>(new Dictionary<string,decimal>() { { "price",222.22m} });
apple.Output();
Console.ReadLine();
在Resolve方法中提供了一个IDictionary的参数,所以我们可以通过Dictionary或者HashTable将参数传递进去。
单个组件进行注册,当我们项目中的类较少的时候还是可以的,但是我们在实际的项目中,往往都是遵循单一化的职责,创建出大量的文件,采用上面的方式将会变成一种灾难。
2.通过规则批量注册(通过类库注册)
container.Register(Classes.FromThisAssembly() //当前程序集,也可以用FromAssemblyInDirectory()等
.InSameNamespaceAs<CatService>() //与CatService类具有相同的命名空间
// .InNamespace("Windsor")//直接指定命名空间
.WithService.DefaultInterfaces()
.LifestyleTransient()); //临时生命周期
var apple= container.Resolve<IAppleService>(new Dictionary<string,decimal>() { { "price",222.22m} });
var cat = container.Resolve<ICatService>();
cat.Eat();
apple.Output();
详细的API可以通过BasedOnDescriptor中的详细说明机型使用

3.通过安装器Installer进新注册
因为测试代码是使用控制台程序进行测试的,上面的两种方式我们把注册的代码直接写在Main方法中,这样的方式耦合性高,同时不方便管理。所以可以采用安装器的方式进行注册
(1)通过接口IWindsorInstaller实现安装器
//定义
public class ServiceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly() //当前程序集,也可以用FromAssemblyInDirectory()等
.InSameNamespaceAs<CatService>() //与CatService类具有相同的命名空间
.WithServiceDefaultInterfaces()//注册所有的默认的接口和实现类
.LifestyleTransient()); //临时生命周期
}
} //注册
//3.通过安装器进行注册
container.Install(FromAssembly.Named("Windsor"));
var apple= container.Resolve<IAppleService>(new Dictionary<string,decimal>() { { "price",222.22m} });
var cat = container.Resolve<ICatService>();
cat.Eat();
apple.Output();
上面通过安装器进注册的时,指定了程序集Windor下面的安装器将会被调用,那么此时有一个问题,如果我的安装器定义在当前类库的文件夹下面是否可以被注册使用呢?
通过测试发现,是可以被注册的。
另一个问题,如果我们的安装器中注册的类出现重复的,那么我们的容器中会不会重复注册?
通过测试发现,不会被重复注册,也不会报错哦。
还有一个问题

会不会报错呢?
答案是不会的,这个可以从CastleWindsor的源码中可以找到,这是有它的的实现机制决定的,会判断重复,维护这一个Dictionary
(2)通过xml配置文件
//使用配置文件 container.Install(Configuration.FromXmlFile("WindsorSetting.xml"));
var cat = container.Resolve<ICatService>();
cat.Eat();
Console.ReadLine();
//定义配置文件WindsorSetting.xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<installers>
<install type="Windsor.ServiceInstaller,Windsor"/>
</installers>
<!--<components>
<component type="Windsor.CatService,Windsor" service="Windsor.ICatService,Windsor">
</component>
</components>-->
</configuration>
type中的字符串,第一个表示的是命名空间下的具体的安装器类,第二个表示程序集名称
上面的代码中我们自定义了xml文件,当然我们可以直接使用项目中app.config
//调用
container.Install(Configuration.FromAppConfig());
var cat = container.Resolve<ICatService>();
cat.Eat();
//配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup> <castle>
<installers>
<install type="Windsor.ServiceInstaller,Windsor"/>
<!--查找该程序集下所有IWindsorInstaller接口的类型进行注册-->
<!--<install assembly="WindsorInstaller"></install>--> <!--查找dll文件-->
<!--<install directory="Extensions" fileMask="*.dll"></install>-->
</installers>
</castle>
</configuration>
二.Windsor中的InstallerFactory的使用
从上面的随笔中我们可以了解到常用的windsor的注入使用的方式,那么其实还有一个很现实的问题,上面的实现方式都是没有注入顺序的,也就是说如果类1用到了另一个注入容器的类2,那么倘若类2如果在类1之后注册,那么将会报错,找不到对应的实例。其实解决这个问题也是好办的,只要我们使用Component一个类一个类的注册就OK了。其实windsor中还提供了另外的方式,那就是InstallerFactory他可以控制注入的顺序。先上代码
public class ServiceFactory:InstallerFactory
{
public override IEnumerable<Type> Select(IEnumerable<Type> installerTypes)
{
var retval = installerTypes.OrderBy(x => this.GetPriority(x));
return retval;
} private int GetPriority(Type type)
{
var attribute = type.GetCustomAttributes(typeof(InstallerPriorityAttribute), false).FirstOrDefault() as InstallerPriorityAttribute;
return attribute != null ? attribute.Priority : InstallerPriorityAttribute.DefaultPriority;
}
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class InstallerPriorityAttribute : Attribute
{
public const int DefaultPriority = ; public int Priority { get; private set; }
public InstallerPriorityAttribute(int priority)
{
this.Priority = priority;
}
}
}
//在Program中注册
container.Install(FromAssembly.This(new ServiceFactory()));


其实在Factory中的Select的方法中会将所有的继承自IWindsorInstaller的类的类型获取到,然后我们通过特性标签的方式对Installer进行排序,这样我们就可以控制Installer被初始化的顺序了。
三.Windsor的拓展
1.泛型的注入
container.Register( Component.For(typeof(ICatService<>)).ImplementedBy(typeof(CatService<>));
2.注册顺序的简单设置
// 取先注册的
container.Register(
Component.For<ICatService>().ImplementedBy<CatService>(),
Component.For<IAppleService>().ImplementedBy<AppleService>()
); // 强制取后注册的
container.Register(
Component.For<ICatService>().ImplementedBy<CatService>(),
Component.For<IAppleService>().Named("SelfDefinedService").ImplementedBy<AppleService>().IsDefault()
);
3.直接注册实例对象
var cat = new CatService();
container.Register(
Component.For<ICatService>().Instance(cat)
);
依赖注入容器之Castle Windsor的更多相关文章
- 基于DDD的.NET开发框架 - ABP依赖注入
返回ABP系列 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ASP.NET Boilerplate是一个用最佳实践和流行技术开发现代WEB应 ...
- 小白初学Ioc、DI、Castle Windsor依赖注入,大神勿入(不适)
过了几天,我又来了.上一篇中有博友提到要分享下属于我们abp初学者的历程,今天抽出点时间写写吧.起初,我是直接去看阳光铭睿的博客,看了一遍下来,感觉好多东西没接触过,接着我又去下了github 里面下 ...
- [Castle Windsor]学习依赖注入
初次尝试使用Castle Windsor实现依赖注入DI,或者叫做控制反转IOC. 参考: https://github.com/castleproject/Windsor/blob/master/d ...
- Castle Windsor 使MVC Controller能够使用依赖注入
以在MVC中使用Castle Windsor为例 1.第一步要想使我们的Controller能够使用依赖注入容器,先定义个WindsorControllerFactory类, using System ...
- Castle.Windsor依赖注入的高级应用_Castle.Windsor.3.1.0
[转]Castle.Windsor依赖注入的高级应用_Castle.Windsor.3.1.0 1. 使用代码方式进行组件注册[依赖服务类] using System; using System.Co ...
- ASP.NET Web API - 使用 Castle Windsor 依赖注入
示例代码 项目启动时,创建依赖注入容器 定义一静态容器 IWindsorContainer private static IWindsorContainer _container; 在 Applica ...
- Castle.Windsor依赖注入的高级应用与生存周期
1. 使用代码方式进行组件注册[依赖服务类] using System; using System.Collections.Generic; using System.Linq; using Syst ...
- MVC Castle依赖注入实现代码
1.MVc 实现依赖注入 public class WindsorControllerFactory : DefaultControllerFactory { private readonly IKe ...
- 对Castle Windsor的Resolve方法的解析时new对象的探讨
依赖注入框架Castle Windsor从容器里解析一个实例时(也就是调用Resolve方法),是通过调用待解析对象的构造函数new一个对象并返回,那么问题是:它是调用哪个构造函数呢? 无参的构造函数 ...
随机推荐
- PL/SQL学习笔记之存储过程
一:PL/SQL的两种子程序 子程序:子程序是执行一个特定功能.任务的程序模块.PL/SQL中有两种子程序:函数 和 过程. 函数:主要用于计算并返回一个值. 过程:没有直接返回值,主要用于执行操 ...
- TCMalloc小记(转)
一. 原理 tcmalloc就是一个内存分配器,管理堆内存,主要影响malloc和free,用于降低频繁分配.释放内存造成的性能损耗,并且有效地控制内存碎片.glibc中的内存分配器是ptmalloc ...
- 让WebService支持Get请求
在C#中,新建一个webservice,默认是post类型的.如果需要支持Get请求,需要对web.config文件进行配置 <system.web> <compilation de ...
- Android——Broadcast Receive 相关知识总结贴
Android系统中的广播(Broadcast)机制简要介绍和学习计划 http://www.apkbus.com/android-99858-1-1.html android----BroadCas ...
- 【Windows】查看Windows上运行程序的异常日志
任何在windows系统上运行的程序,只要发生异常导致程序异常终止,windows都会在日志中详细记录这个异常.可以在计算机管理中查看,如图:也可以在操作中心查看,如图:
- R语言编程艺术#02#矩阵(matrix)和数组(array)
矩阵(matrix)是一种特殊的向量,包含两个附加的属性:行数和列数.所以矩阵也是和向量一样,有模式(数据类型)的概念.(但反过来,向量却不能看作是只有一列或一行的矩阵. 数组(array)是R里更一 ...
- fft ocean注解
针对这两篇教程: http://www.keithlantz.net/2011/10/ocean-simulation-part-one-using-the-discrete-fourier-tran ...
- json简介及JsonCpp用法
[时间:2017-04] [状态:Open] [关键词:数据交换格式,json,jsoncpp,c++,json解析,OpenSource] json简介 本文仅仅是添加我个人对json格式的理解,更 ...
- 1. Tensorflow高效流水线Pipeline
1. Tensorflow高效流水线Pipeline 2. Tensorflow的数据处理中的Dataset和Iterator 3. Tensorflow生成TFRecord 4. Tensorflo ...
- pandas 学习总结
pandas 学习总结 作者:csj 更新时间:2018.04.02 shenzhen email:59888745@qq.com home: http://www.cnblogs.com/csj0 ...