MVC中 依赖注入(IOC)

1)Unity 配置文件

<?xml version="1.0" encoding="utf-8"?>
<unity>
  <typeAliases>
    <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity"/>
    <!--action的构造函数需要接口定义,依赖注入需要接口-->
    <typeAlias alias="IFoo" type="MyTest.BizInterfaces.IFoo,MyTest.BizInterfaces"/>
  
  </typeAliases>
  <containers>
    <container name="containerOne">
      <types>
        <!--action的构造函数需要接口定义,依赖注入需要接口-->
        <type type="IFoo" mapTo="MyTest.Business.Foo, MyTest.Business"/> 
      </types>
    </container>
  </containers>
</unity>

2)UnityConfigurator

namespace MyTest.Common.IOC
{
    public class UnityConfigurator
    {
        public static IUnityContainer CreateContainer()
        {
            IUnityContainer parentContainer = new UnityContainer();
            IUnityContainer childContainer = parentContainer.CreateChildContainer();
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            section.Configure(childContainer, "containerOne");
            return childContainer;
        }
    }
}

3)UnityControllerFactory

 namespace MyTest.Common.IOC
{
    public class UnityControllerFactory : DefaultControllerFactory
    {
        readonly IUnityContainer container;

        public UnityControllerFactory(IUnityContainer container)
        {
            this.container = container;
            var controllerTypes =
               from t in Assembly.GetExecutingAssembly().GetTypes()
               where typeof(IController).IsAssignableFrom(t)
               select t;
            foreach (var t in controllerTypes)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine("RegisterType: " + t.Name);
#endif
                container.RegisterType(t);
            }
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null) return null;
            return (IController)container.Resolve(controllerType);
        }
    }
}

4) Under Register Routes

 public static void RegisterRoutes(RouteCollection routes)
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            Infratructure.RouteConfigurator.RegisterRoutes(RouteTable.Routes);

            IUnityContainer container = UnityConfigurator.CreateContainer();
            UnityControllerFactory factory = new UnityControllerFactory(container);
            ControllerBuilder.Current.SetControllerFactory(factory);
        }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。