Castle windsor快速入门

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接口
                .Configure(c => c.LifestylePerWebRequest()));//每次请求创建一个Controller实例

            container.Register(Component.For().ImplementedBy());
        }
    }
}
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)