一、简介
Castle是.net平台上的一个开源项目,为企业级开发和WEB应用程序开发提供完整的服务,用于提供IOC的解决方案.IOC被称为控制反转或者依赖注入(Dependency Injection)。
Windsor是Castle 的一个IOC容器。它构建于MicroKernel之上,功能非常之强大,能检测类并了解使用这些类时需要什么参数,检测类型和类型之间工作依赖性,并提供服务或者发生错误时提供预警的机制。
官网:http://www.castleproject.org
源码: https://github.com/castleproject/Core
源码: https://github.com/castleproject/Windsor
推荐教程:http://www.cnblogs.com/Terrylee/archive/2006/04/28/387503.html
二、实例
1.创建项目
在程序包管理器控制台引用Castle.Windsor
Install-Package Castle.Windsor -Version 4.1.0
2.创建类库Business,并在web项目引用,新建接口IUserService和实现类UserService
public interface IUserService
{
string Display(string mes);
}
public class UserService : IUserService
{
public string Display(string mes)
{
return "User say:" + mes;
}
}
3.添加安装类
安装的配置比较简单,无非是寻找安装类,并执行安装并获取容器,所有的安装类都需要继承自IWindsorInstaller,添加CustomMvcInstaller ,如下:
namespace MvcWeb.CastleWindsor
{
public class CustomMvcInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<IUserService>().ImplementedBy<UserService>()
);
}
}
public class WindsorInit
{
private static WindsorContainer \_container;
public static WindsorContainer GetContainer()
{
if (\_container == null)
{
\_container \= new WindsorContainer();
\_container.Install(
FromAssembly.This()
);
}
return \_container;
}
public void CloseContex()
{
\_container.Dispose();
}
}
}
4.修改home控制器
public class HomeController : Controller
{
private IUserService \_userService;
public HomeController()
{
WindsorContainer container \= WindsorInit.GetContainer();
\_userService \= container.Resolve<IUserService>(new Arguments(new { }));
}
public ActionResult Index()
{
ViewBag.Name \= \_userService.Display("I am coming by Windsor");
return View();
}
index.cshtml修改如下
<div class\="jumbotron"\>
<h1>ASP.NET </h1>
<h3>@ViewBag.Name </h3>
.......
大功造成,可以访问首页了
源码下载:https://gitee.com/zmsofts/XinCunShanNianDaiMa/blob/master/IocDemo.rar
参考文章:
http://www.cnblogs.com/wuxilin/archive/2006/04/20/380475.html
http://blog.csdn.net/eye_cng/article/details/44277151
http://blog.csdn.net/eye_cng/article/details/44277371
https://www.cnblogs.com/lanpingwang/p/6533738.html
https://www.cnblogs.com/ceci/p/6877903.html