概述
1.创建MVC项目,安装Castle Windsor
2.创建CastleWindsor文件夹
在ASP.NET MVC中,每次请求,DefaultControllerFactory都会为我们创建controller实例,我们需要自定义一个派生自DefaultControllerFactory的类,让Castle Windsor帮我们生成controller实例。创建WindsorControllerFactory类,并集成子DeafaultControllerFactory
namespace CastleApp.CastleWindsor
{
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IKernel _ikernel;
public WindsorControllerFactory(IKernel ikernel)
{
_ikernel = ikernel;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
throw new HttpException(404, string.Format("当前对{0}的请求不存在", requestContext.HttpContext.Request.Path));
}
return (IController)_ikernel.Resolve(controllerType);
}
public override void ReleaseController(IController controller)
{
_ikernel.ReleaseComponent(controller);
base.ReleaseController(controller);
}
}
}
3.在global.asax中:生成Castle Windsor实例,赋值给自定义ControllerFactory的构造函数,并在Application结束时销毁该Castle Windsor实例。
public class MvcApplication : System.Web.HttpApplication
{
public static IWindsorContainer _container;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
MvcApplication.BootstrapContainer();
}
private static void BootstrapContainer()
{
_container = new WindsorContainer();
_container.Install(FromAssembly.This());
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container.Kernel));
}
protected void Application_End()
{
_container.Dispose();
}
}
4.需要告诉Castle Windsor在何种条件下,以怎样的方式注册依赖。Castle Windsor提供了IWindsorInstaller接口。在CastleWindsor文件夹下创建实现该接口的类。
namespace CastleApp.CastleWindsor
{
public class ControllerInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly() //在哪里找寻接口或类
.BasedOn<IController>() //实现IController接口
.Configure(c => c.LifestylePerWebRequest()));//每次请求创建一个Controller实例
container.Register(Component.For<IContactManager>().ImplementedBy<ContactManager>());
}
}
}
5.创建接口,创建controller
public class AboutController : Controller
{
private IContactManager contactManager;
public AboutController(IContactManager contactManager)
{
this.contactManager = contactManager;
}
public ActionResult Index()
{
ViewBag.name= contactManager.ShowName("123");
return View();
}
}
最后
以上就是威武万宝路为你收集整理的Castle windsor快速入门的全部内容,希望文章能够帮你解决Castle windsor快速入门所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复