zoukankan      html  css  js  c++  java
  • 在 MVC 控制器中使用 构造函数时行依赖注入 (IoC)

     在 Controller 中使用 构造函数进行依赖注入 (IoC)

    1. Controller 代码:

      ICard card;
            ICardCategory cardCategory;
            public CardController(ICard card, ICardCategory cardCategory)
            {
                this.card = card;
                this.cardCategory = cardCategory;
            }
    

     接口 ICard , ICardCateogry 是一个普通的接口,没有继承或实现任何接口,而需要做的就是在 Gloable.cs 文件中解析依赖, 为了方便复用,将解析依赖封装成一个类,然后在 Gloable.cs 文件中注册,在这个示例中,使用的是 Unity 进行依赖注入,完整的代码如下:

    using Microsoft.Practices.Unity;
    using System;
    using System.Collections.Generic;
    //using System.Web.Http.Dependencies;
    using System.Web;
    using System.Web.Mvc;
    
    namespace SnsManage.Resolver
    {
       /// <summary>
       ///  Dependency Injection  Resolver Container 
       /// </summary>
        public class UnityResolver : IDependencyResolver
        {
            protected IUnityContainer container;
    
            public UnityResolver(IUnityContainer container)
            {
                if (container == null)
                {
                    throw new ArgumentNullException("container");
                }
                this.container = container;
            }
    
            public object GetService(Type serviceType)
            {
                try
                {
                    return container.Resolve(serviceType);
                }
                catch (ResolutionFailedException)
                {
                    return null;
                }
            }
    
            public IEnumerable<object> GetServices(Type serviceType)
            {
                try
                {
                    return container.ResolveAll(serviceType);
                }
                catch (ResolutionFailedException)
                {
                    return new List<object>();
                }
            }
    
            //public IDependencyScope BeginScope()
            //{
            //    var child = container.CreateChildContainer();
            //    return new UnityResolver(child);
            //}
    
            //public void Dispose()
            //{
            //    container.Dispose();
            //}
    
    
    
    
            //private const string HttpContextKey = "perRequestContainer";
    
            //private readonly IUnityContainer container;
    
            //public UnityResolver(IUnityContainer container)
            //{
            //    this.container = container;
            //}
    
            //public object GetService(Type serviceType)
            //{
            //    if (typeof(IController).IsAssignableFrom(serviceType))
            //    {
            //        return ChildContainer.Resolve(serviceType);
            //    }
    
            //    return IsRegistered(serviceType) ? ChildContainer.Resolve(serviceType) : null;            
            //}
    
            //public IEnumerable<object> GetServices(Type serviceType)
            //{
            //    if (IsRegistered(serviceType))
            //    {
            //        yield return ChildContainer.Resolve(serviceType);
            //    }
    
            //    foreach (var service in ChildContainer.ResolveAll(serviceType))
            //    {
            //        yield return service;
            //    }
            //}
    
            //protected IUnityContainer ChildContainer
            //{
            //    get
            //    {
            //        var childContainer = HttpContext.Current.Items[HttpContextKey] as IUnityContainer;
    
            //        if (childContainer == null)
            //        {
            //            HttpContext.Current.Items[HttpContextKey] = childContainer = container.CreateChildContainer();
            //        }
    
            //        return childContainer;
            //    }
            //}        
    
            //public static void DisposeOfChildContainer()
            //{
            //    var childContainer = HttpContext.Current.Items[HttpContextKey] as IUnityContainer;
    
            //    if (childContainer != null)
            //    {
            //        childContainer.Dispose();
            //    }
            //}
    
            //private bool IsRegistered(Type typeToCheck)
            //{
            //    var isRegistered = true;
    
            //    if (typeToCheck.IsInterface || typeToCheck.IsAbstract)
            //    {
            //        isRegistered = ChildContainer.IsRegistered(typeToCheck);
    
            //        if (!isRegistered && typeToCheck.IsGenericType)
            //        {
            //            var openGenericType = typeToCheck.GetGenericTypeDefinition();
    
            //            isRegistered = ChildContainer.IsRegistered(openGenericType);
            //        }
            //    }
    
            //    return isRegistered;
            //}
        }
    }
    View Code

    然后在 App_Start 文件中添加一个配置类, UnityConfig.cs, 其中的代码如下:

        public static class UnityConfig
        {
           /// <summary>
           ///  Dependency Injection 
           /// </summary>
            public static void RegisterComponents()
            {
                var container = new UnityContainer();
                
                // register all your components with the container here
                // it is NOT necessary to register your controllers
                
                // e.g. container.RegisterType<ITestService, TestService>();
                
                container.RegisterType<IUser, UserService>( new HierarchicalLifetimeManager());
    
                DependencyResolver.SetResolver(new UnityResolver(container));
                
            }
        }

    最后在 Global.asax 文件中注册

                UnityConfig.RegisterComponents();
    
  • 相关阅读:
    MyBatis之三:多表联合查询
    MyBatis之二:简单增删改查
    MyBatis之一:入门
    如何用Maven创建web项目(具体步骤)
    Maven3.2创建webapp项目过程中问题以及解决方案
    纯前端下载数据Excel文档
    centos7 yum无法正常工作
    Element ui table selection 分页支持保存已经选中的数据,同时支持随时删除选中的数据,并设置默认选择
    删除排序数组中的重复选项
    列表数据(包含父节点关系)转化为树形结构
  • 原文地址:https://www.cnblogs.com/wisdo/p/4374475.html
Copyright © 2011-2022 走看看