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);
- }
- }
- }
- 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();
- }
- }
- 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>());
- }
- }
- }
- public class AboutController : Controller
- {
- private IContactManager contactManager;
- public AboutController(IContactManager contactManager)
- {
- this.contactManager = contactManager;
- }
- public ActionResult Index()
- {
- ViewBag.name= contactManager.ShowName("123");
- return View();
- }
- }