zoukankan      html  css  js  c++  java
  • 你必须要知道的架构知识~第五章 依赖住入在这个时候出场了

    这段时间确实忙,以至于连写博客的时间都没有了,今天正好有点时间,有第五章依赖住入简单的说一下,主要分两块,一是依赖住入的概念,什么时候使用依赖注入,第二个问题是通过一个使用Unity的实例来让大家对依赖注入有一个很直观的认识。

    一 概念:依赖注入,即Dependency Injection,即DI,有时也叫它控制反转,一般用IoC来实现对象的创建工作,我们知道一个类,要想被实例化我们可以用new关键字,例如一个数据操作接口规范interface IRepository{},其中有一个SQLSERVER的数据操作去实现了它class  SQLRepository:IRepository{},而客户电脑上装的是oracle,所以没办法,我又为oracle实现了一个数据操作,即class ORACLERepository:IRepository{},如果我们希望创建一个SQLRepository实例,我们可以有至少两种方法,即:

    SQLRepository sqlRepository=new SQLRepository();

    IRepository  iRepository =new SQLRepository();

    从上面两种创建对象的方法可以知道第二次更面向对象,因为iRepository 不仅可以生成SQLRepository对象,它还可以生成所有继承自IRepository  的对象,但如果我们希望在程序运行中,或者在今天很方便的是实现SQLRepository与ORACLERepository之间的切换,那需要对程序进行很大的手术,这事实上就是类的高耦合,为了解决上面的问题,我们引入了一种在程序”运行时”动态改变对象创建方式的技术,这种技术我们成为“控制反转”,也就是依赖注入,目前比较流行的IoC容器有Unity,Pico Containe,JBos等,我们以Unity为例来学习一下依赖注入在项目中的应用。

    二 依赖注入在项目中的应用

    image

    我们看到,这就是一个依赖注入的项目,它一般在项目中是对所有层可见的,在这个项目中,我们的Service(BLL)层通过Ioc容器实现了对Data(DAL)层的控制反转,它将需要实现IoC的类放在配置文件中,这样在程序运行时可以动态的随时调整。

    image

    我们看到,它会在配置文件中找到repositoryContainer这个节点,然后把它的值取出并反射成我们的对象,下面是配置文件中的代码片断

      <configSections>
        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration, Version=1.1.0.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      </configSections>
      <unity>
        <containers>
          <container name="repositoryContainer">
            <types>
              <type type="TESTWEB.Controllers.IPeople,TESTWEB" mapTo="TESTWEB.Controllers.PeopleChina,TESTWEB"></type>
            </types>
          </container>
        </containers>
      </unity>
    以下是实现Unity依赖注入的DLL
    image 

    事实上,依赖注入并不神秘,只要我们知道什么时候用它,这是最重要的。

    下面分享一个创建unity容器的代码片断

    /// <summary>
           /// Initializes container.
           /// </summary>
           public override void Initialize()
           {
               OnBeforeInitialized(new ContainerEventArgs(this, ContainerType.Unity));
    
               if (CurrentContext.Application[Name] == null)
               {
                   lock (_synlock)
                   {
                       if (CurrentContext.Application[Name] == null)
                       {
                           IUnityContainer currentContainer = new UnityContainer();
                           UnityConfigurationSection section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
                           section.Containers[Name].Configure(currentContainer);
                           CurrentContext.Application[Name] = currentContainer;
                       }
                   }
               }
    
               OnAfterInitialized(new ContainerEventArgs(this, ContainerType.Unity));
           }
    
           /// <summary>
           /// Resolves this instance.
           /// </summary>
           /// <returns></returns>
           public override T Resolve<T>()
           {
               try
               {
                   Initialize();
    
                   IUnityContainer currentContainer = CurrentContext.Application[Name] as IUnityContainer;
                   return currentContainer.Resolve<T>();
               }
               catch (Exception ex)
               {
                   OnResolveFailed(new ContainerFailedEventArgs(this, ContainerType.Unity, ex));
                   return default(T);
               }
           }

    在Initialize()方法中使用了C#的事件,在设置容器名称之前与之前各触发了一个事件,这样当有其它地方对这两个事件订阅时,会在初始化容器时,被同时触发。呵呵。够巧妙吧!

  • 相关阅读:
    maven安装与配置
    git客户端安装
    linux-更改文件属性-chattr与lsattr
    乐观锁-version的使用
    Project 專業名詞
    從 kernel source code 查出 版本號碼
    Bit banging
    Push pull, open drain circuit, pull up, pull down resistor
    Current Sourcing (拉電流) and Current Sinking(灌電流)
    學習 DT device tree 以 ST 的開發板 STM32F429i-disc1 為例
  • 原文地址:https://www.cnblogs.com/lori/p/2410812.html
Copyright © 2011-2022 走看看