.NET IOC 框架 —— Castle Windsor配置

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qi_moumou/article/details/80271639
一. 常见的IOC框架为Castle Windsor和Spring .Net,只不过后者比较依赖配置文件
二.为什么要使用IOC框架

1.普通的实例化方式 IMyService myService = new MyService()有一个弊端:接口与实现没有分离

2.如果使用Castle Windsor框架,实例化方式为:

IMyService myService = container.Resolve<IMyService>( );

如果接口对应多个实现类,实例化方式为:

IMyService[ ] myServices = container.ResolveAll<IMyService>( );

三. Castle Windsor

1.创建一个项目,使用Nuget引入Castle Windsor,同时需要安装Microsoft.AspNet.Mvc;

2.创建一个类继承DefaultControllerFactory:因为在ASP.NET MVC中,每次请求,DefaultControllerFactory都会创建controller的实例,所以在项目中新建一个WindsorControllerFactory类继承DefaultControllerFactory,让Castle Windsor来创建controller的实例;

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

namespace PersonalPlanning.Init.IOC
{
    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)
            {
                return base.GetControllerInstance(requestContext, null);
            }
            return (IController) _ikernel.Resolve(controllerType);
        }

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

}

3.在Global.asax配置文件中的Application_Start方法中添加

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

           //Init a IOC container
           _container = new WindsorContainer().Install(FromAssembly.This());

           //Finish register of the IWindsorInstall

           ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container.Kernel));

  同时在Application_End中销毁_container

          _container.Dispose();


4.在IOC文件夹中创建一个继承IWindsorInstaller的类,如ControllerInstaller,并实现接口的方法:

    public class ControllerInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            
        }
    }









展开阅读全文

没有更多推荐了,返回首页