ASP.NET MVC Castle Windsor 教程

一、【转】ASP.NET MVC中使用Castle Windsor

二、【转】Castle Windsor之组件注册

平常用Inject比较多,今天接触到了Castle Windsor。本篇就来体验其在ASP.NET MVC中的应用过程。

Visual Studio 2012创建一个ASP.NET MVC 4网站。

通过NuGet安装Castle Windsor。

在当前项目下创建一个名称为"IOC"的文件夹。

在ASP.NET MVC中,每次请求,DefaultControllerFactory都会为我们创建controller实例,我们需要自定义一个派生自DefaultControllerFactory的类,让Castle Windsor帮我们生成controller实例。

using System.Web;
using System.Web.Mvc;
using Castle.MicroKernel;

namespace MyCastleWindsor.IOC
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel _kernel;

        public WindsorControllerFactory(IKernel kernel)
        {
            _kernel = kernel;
        }

        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, System.Type controllerType)
        {
            if (controllerType == null)
            {
                throw  new HttpException(404,string.Format("当前对{0}的请求不存在",requestContext.HttpContext.Request.Path));
            }
            return (IController)_kernel.Resolve(controllerType);
        }

        public override void ReleaseController(IController controller)
        {
            _kernel.ReleaseComponent(controller);
            base.ReleaseController(controller);
        }
    }
}

现在需要在全局中生成Castle Windsor实例,赋值给自定义ControllerFactory的构造函数,并在Application结束时销毁该Castle Windsor实例。

   public class MvcApplication : System.Web.HttpApplication
    {
        private IWindsorContainer _container;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //初始化一个IOC容器
            _container = new WindsorContainer().Install(FromAssembly.This());

            //完成IWindsorInstaller接口中的注册
            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container.Kernel));
        }

        protected void Application_End()
        {
            _container.Dispose();
        }
    }

现在,需要告诉Castle Windsor在何种条件下,以怎样的方式注册依赖。Castle Windsor提供了IWindsorInstaller接口。在IOC文件夹下创建实现该接口的类。

using System.Web.Mvc;
using Castle.MicroKernel.Registration;
using MyCastleWindsor.Controllers;

namespace MyCastleWindsor.IOC
{
    public class ControllerInstaller : IWindsorInstaller
    {

        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly() //在哪里找寻接口或类
                .BasedOn<IController>() //实现IController接口
                .If(Component.IsInSameNamespaceAs<HomeController>()) //与HomeController在同一个命名空间
                .If(t => t.Name.EndsWith("Controller")) //以"Controller"结尾
                .Configure(c => c.LifestylePerWebRequest()));//每次请求创建一个Controller实例
        }
    }
}

而实际上,在全局文件中,当运行Install(FromAssembly.This())方法时,会执行 IWindsorInstaller的Install接口方法。

public interface IContactManager
{}

接口的实现类:

public class ContactManager : IContactManager
{}

在某个控制器中,通过构造函数注入依赖,我们希望这样写:

private IContactManager contactManager;

public HomeController(IContactManager contactManager)
{
    this.contactManager = contactManager;
}

现在需要注册IContactManager和ContactManager。可以通过反射方式注册依赖。

using System.Web.Mvc;
using Castle.MicroKernel.Registration;
using MyCastleWindsor.Controllers;

namespace MyCastleWindsor.IOC
{
    public class ControllerInstaller : IWindsorInstaller
    {

        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {

            container.Register(Classes.FromThisAssembly()
                .Where(t => t.Name.EndsWith("Manager"))
                .WithServiceDefaultInterfaces()
                .Configure(c => c.LifestyleTransient()));
        }
    }
}

关于Castle Windsor的应用大致如下:

→ 继承ASP.NET MVC的ControllerFactory,通过构造函数传入Castle Windsor的IKernel,让其解析出IController类型控制器。

→ 通过实现Castle Windsor的IWindsorInstaller接口,通过反射注册依赖关系。

→ 在全局文件中初始化Castle Windsor的实例,并注册自定义的ControllerFactory。

http://www.bkjia.com/Asp_Netjc/1035464.htmlwww.bkjia.comtruehttp://www.bkjia.com/Asp_Netjc/1035464.htmlTechArticle在ASP.NET MVC中使用Castle Windsor,mvcwindsor 平常用Inject比较多,今天接触到了Castle Windsor。本篇就来体验其在ASP.NET MVC中的应用过程。 Visual Stu...
原文地址:https://www.cnblogs.com/xdot/p/7338667.html