在Castle中包含了一组开发框架,它里面的IOC容器是Windsor。在Windsor中提出了自动装配的概念,由容器来自动管理组件之间的依赖关系,无需用户去编写XML配置文件或者经过Attribute来指定容器之间的依赖关系。这样在使用上很是的简单,同时也带了一些问题,做为开发人员的咱们没法控制组件的依赖关系。c#
简单使用:
框架
1.添加Castle.Core.dll,Castle.Windsor两个引用。函数
2.建立被用于注入的接口和其实现。
spa
3.在程序的入口处(winform在Main函数下,Web Application在Application_start()下)添加以下代码code
IWindsorContainer container = new WindsorContainer(); //下面为你要注册的组件,即注入容器的配置。 //“WindowsFormsApplication1” 为程序集名称,Form为要注册类的基类 container.Register(AllTypes.FromAssemblyNamed("WindowsFormsApplication1") .BasedOn<Form>().WithService.DefaultInterfaces()); //“Tasks”为你的程序集名称,“Service”为你的“IService”接口的实现类 container.Register(AllTypes.FromAssemblyNamed("Tasks").Pick() .If(t => t.Name.EndsWith("Service")) .WithService.DefaultInterfaces());
4.在调用出实现注入,并调用。
orm
1)属性/Setter注入: 接口
public ITestService TestService { get; set; } TestService.GetMethod();//调用TestService中的GetMethod()方法
2)构造器注入:开发
public partial class Form1 : Form { private ITestService _service; public Form1(ITestService testService) { InitializeComponent(); _service = testService; _service.GetMethod();//调用TestService中的GetMethod()方法 } }