ASP.NET MVC IoC处理方式

70 篇文章 0 订阅

  
1、通过NuGet 加载程序包: Unity ;

2、建立一个反转类:  NDependencyResolver.cs


    public class NDependencyResolver : IDependencyResolver
    {
            #region IDependencyResolver 成员

            /// <summary>
            /// 依赖注入容器
            /// </summary>
            private IUnityContainer _unityContainer;


            /// <summary>
            /// 构造
            /// </summary>
            /// <param name="aUnityContainer">依赖注入容器</param>
            public NDependencyResolver(UnityContainer aUnityContainer)
            {
                _unityContainer = aUnityContainer;
            }



            public object GetService(Type aServiceType)
            {
                try
                {
                    return _unityContainer.Resolve(aServiceType);
                }
                catch
                {
                    /// 按微软的要求,此方法,在没有解析到任何对象的情况下,必须返回 null,必须这么做!!!!
                    return null;
                }
            }


            public IEnumerable<object> GetServices(Type aServiceType)
            {
                try
                {
                    return _unityContainer.ResolveAll(aServiceType);
                }
                catch
                {
                    /// 按微软的要求,此方法,在没有解析到任何对象的情况下,必须返回空集合,必须这么做!!!!
                    return new List<object>();
                }
            }

            #endregion

        }


3、全局Global.asax.cs 中进行依赖注入初始化:

    public class MvcApplication : System.Web.HttpApplication
    {
        ..............
        protected void Application_Start()
        {
            .........
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //加载依赖注入
           <span style="color:#ff0000;"> RegisterDependency();</span>
        }

        <span style="color:#ff0000;">/// <summary>
        /// IOC 容器初始化
        /// </summary>
        private static UnityContainer _Container;
        public static UnityContainer Container
        {
            get
            {
                if (_Container == null)
                {
                    _Container = new UnityContainer();
                }
                return _Container;
            }
        }

        protected void RegisterDependency()
        {
            Container.RegisterType</span><span style="color:#009900;"><WarehouseI, WarehouseIntFace></span><span style="color:#ff0000;">();
            DependencyResolver.SetResolver(</span><span style="color:#009900;">new NDependencyResolver</span><span style="color:#ff0000;">(Container));
        }</span>

    }


4、调运action中加入依赖注入:

      
        [Dependency]
        public WarehouseI warehouseIntFace { get; set; }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值