码迷,mamicode.com
首页 > 编程语言 > 详细

微软unity 注入mvc

时间:2016-04-18 20:45:45      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

首先获取开源unity ,引用技术分享

新建UnityDependencyResolver 继承IDependencyResolver,代码如下:

 public class UnityDependencyResolver : IDependencyResolver
    {
        IUnityContainer container;

        public UnityDependencyResolver(IUnityContainer container)
        {
            this.container = container;
        }
        public object GetService(Type serviceType)
        {
            
            try
            {
                return container.Resolve(serviceType);
            }
            catch (Exception)
            {
                return null;
            }
          
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return container.ResolveAll(serviceType);
        }
    }

 

写一个注册类

 public class Bootstrapper
    {

        private static IUnityContainer container;
        /// <summary>
        /// 初始化IOC
        /// </summary>
        public static void Init()
        {
            //container = BuildUnityContainer();
            container = new UnityContainer();
            RegisterDependency();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }

        /// <summary>
        /// 所有的注册
        /// </summary>
        private static void RegisterDependency()
        {
            container.RegisterType<IDoctorTeamType, DoctorTeamType>();
        }
    }

放到启动类 中执行Bootstrapper.Init();就可以了

微软unity 注入mvc

标签:

原文地址:http://www.cnblogs.com/zuolijun/p/5405557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!