Microsoft.Practices.Unity官方网站

http://unity.codeplex.com/

 

Unity是微软Patterns & Practices团队所开发的一个轻量级的,并且可扩展的依赖注入(Dependency Injection)容器,它支持常用的三种依赖注入方式:构造器注入(Constructor Injection)、属性注入(Property Injection),以及方法调用注入(Method Call Injection).现在Unity最新的版本的1.2版,可以在微软的开源站点http://unity.codeplex.com下载最新的发布版本和文档。通过使用Unity,我们能轻松构建松耦合结构的程序,从而让整个程序框架变得清晰和易于维护。

在平常的软件编码过程中,程序的逻辑往往很复杂,尤其是大型项目的开发中,一个模块常常会去引用其他的模块,假设我们有一个监控器类,用来监控CPU的温度,当温度达到预警的范围时,监控器有一个报警的方法,方法里面通过短信提醒器,以发送短信的方式通知维护人员。于是就出现了下面这样一段最为常见的代码:

<span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> Monitor
   2:  {
<span class="lnum">   3:  </span>       <span class="kwrd">public</span> <span class="kwrd">void</span> Alarm()
   4:         {
<span class="lnum">   5:  </span>               SMSNotify notify = <span class="kwrd">new</span> SMSNotify();
   6:                 notify.Send();
<span class="lnum">   7:  </span>        }
   8:  }

在Monitor类中,直接引用到了一个短信提醒器的类,这是最为不灵活和最不易于扩展的一种方式。或许我们想到了面向接口编程,利用多态的好处,可以提供灵活的不同子类的实现,增加代码扩展性等等。但是说到底,接口一定是需要实现的,也就是如下语句迟早要执行:

<span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">void</span> Alarm()
   2:  {
<span class="lnum">   3:  </span>       INotify notify = <span class="kwrd">new</span> SMSNotify();
   4:         notify.Send();
<span class="lnum">   5:  </span>}

这样看来,在实现INotify这个接口的时候,仍然需要具体的类来实现,而这样的代码在程序编译的时候就已经固定下来,如果以后需要使用新的提醒器,仍旧需要修改源代码并重新编译。并且在我们的Monitor类中,明显依赖SMSNotify类,二者之间的耦合度非常紧密。因此Ioc(控制反转)模式被提出用来解决这种问题,也即把接口的具体实现延缓到运行时,接口的实现类是在运行时被装载的。这样,就算有了新的实现类,也不需要更改调用者的代码(可以在Unity中使用配置文件的方式实现)。这种Ioc模式可以被形象的比喻为:接口就像一个空壳,而在具体实现时,向这个空壳注入内容,而让它成为一个真正的实体。这种模式也被形象的称为:依赖注入。通过使用Unity,我们能构建松耦合的软件,并且对象之间相互关联的细节,我们也不必关心,可以交由依赖注入容器全权负责。

前面也提到了依赖注入常用的三种形式:构造器注入、属性注入和方法调用注入,我们可以通过例子来实现这三种形式的注入。还是以上面的场景为例,我们的几个类和接口如下图:

1

1.Constructor Injection

IMonitor接口定义:

<span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">interface</span> IMonitor
   2:  {
<span class="lnum">   3:  </span>    <span class="kwrd">void</span> Alarm();
   4:  }

Monitor类:

<span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> Monitor : IMonitor
   2:  {
<span class="lnum">   3:  </span>    <span class="kwrd">private</span> INotify notify;
   4:  
<span class="lnum">   5:  </span>    <span class="kwrd">public</span> Monitor(INotify n)
   6:      {
<span class="lnum">   7:  </span>        notify = n;
   8:      }
<span class="lnum">   9:  </span>
  10:      public void Alarm()
<span class="lnum">  11:  </span>    {
  12:          notify.Send();
<span class="lnum">  13:  </span>    }
  14:  }

INotify接口定义:

<span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">interface</span> INotify
   2:  {
<span class="lnum">   3:  </span>    <span class="kwrd">void</span> Send();
   4:  }

EmailNotify类:

<span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> EmailNotify : INotify
   2:  {
<span class="lnum">   3:  </span>    <span class="kwrd">public</span> <span class="kwrd">void</span> Send()
   4:      {
<span class="lnum">   5:  </span>        Console.WriteLine(<span class="str">"Send Email Notify..."</span>);
   6:      }
<span class="lnum">   7:  </span>}

SMSNotify类:

<span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> SMSNotify : INotify
   2:  {
<span class="lnum">   3:  </span>    <span class="kwrd">public</span> <span class="kwrd">void</span> Send()
   4:      {
<span class="lnum">   5:  </span>        Console.WriteLine(<span class="str">"Send SMS Notify..."</span>);
   6:      }
<span class="lnum">   7:  </span>}

可以看到,在Monitor类的构造函数里面,传入的参数是一个INotify接口类型,Alarm方法,调用了实现类的Send方法,但具体调用哪一个实现类的Send方法,只有在注入实体后才知道。Unity容器中,通常使用RegisterType和Resolve方法来分别注册和获取实例,并且这两个方法有很多泛型和非泛型的重载,具体的类型和参数,可以参考Unity的官方帮助文档。

现在我们向Monitor的构造函数注入实现INotify接口的实例:

<span class="lnum">   1:  </span><span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
   2:  {
<span class="lnum">   3:  </span>    IUnityContainer container = <span class="kwrd">new</span> UnityContainer();
   4:      container.RegisterType<IMonitor, Monitor>().RegisterType<INotify, SMSNotify>();
<span class="lnum">   5:  </span>
   6:      IMonitor monitor = container.Resolve<IMonitor>();
<span class="lnum">   7:  </span>    monitor.Alarm();
   8:  
<span class="lnum">   9:  </span>    Console.ReadLine();
  10:  }

代码中我们注入的INotify实例是SMSNotify类的实例,然后调用monitor.Alrarm(),里面会调用notify.Send().
运行查看结果:
2
上面是针对单个构造函数的情况,如果有多个构造函数,需要指明哪个构造函数是需要被注入的,也即需要在指定被注入的构造函数加上attribute:InjectionConstructor

<span class="lnum">   1:  </span><span class="kwrd">public</span> Monitor(INotify n, <span class="kwrd">string</span> name)
   2:  {
<span class="lnum">   3:  </span>    notify = n;
   4:  }
<span class="lnum">   5:  </span>
   6:  [InjectionConstructor]
<span class="lnum">   7:  </span><span class="kwrd">public</span> Monitor(INotify n)
   8:  {
<span class="lnum">   9:  </span>    notify = n;
  10:  }

运行后可得到一样的结果.

2.Property Injection

通过属性注入,我们需要加上attribute: Dependency,使得Unity容器在获取类对象实例时,自动实例化该属性所依赖的对象,并注入到属性中。

修改Monitor类,实现下面的代码:

<span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> Monitor : IMonitor
   2:  {
<span class="lnum">   3:  </span>    [Dependency]
   4:      public INotify Notify { get; set; }
<span class="lnum">   5:  </span>
   6:      public void Alarm()
<span class="lnum">   7:  </span>    {
   8:          Notify.Send();
<span class="lnum">   9:  </span>    }
  10:  }

再在Main函数里面,修改原有的代码,这次我们让容器注入EmailNotify实例:

<span class="lnum">   1:  </span>container.RegisterType<INotify, EmailNotify>();

运行查看结果:
3还有一个比较方便的地方,可以为Dependency特性指定名称,这样,在注入时,会将RegisterType所指定的对应名称的实体进行注入,例如:

<span class="lnum">   1:  </span>    <span class="kwrd">public</span> <span class="kwrd">class</span> Monitor : IMonitor
   2:      {
<span class="lnum">   3:  </span>        [Dependency(<span class="str">"SMS"</span>)]
   4:          public INotify Notify { get; set; }
<span class="lnum">   5:  </span>
   6:          public void Alarm()
<span class="lnum">   7:  </span>        {
   8:              Notify.Send();
<span class="lnum">   9:  </span>        }
  10:      }

修改Main函数,在RegisterType函数中指定注入名称:

<span class="lnum">   1:  </span>            container.RegisterType<INotify, EmailNotify>(<span class="str">"Email"</span>);
   2:              container.RegisterType<INotify, SMSNotify>("SMS");

运行查看结果:
2

3.Method Call Injection

Method Call Injection注入的时机和Constructor Injection有一定的区别,构造函数注入,是在容器创建实例的时候,而方法调用注入,是在方法被调用的时候。实现方法调用注入,需要在指定注入的方法前加上attribute: InjectionMethod

修改Monitor类的代码如下:

<span class="lnum">   1:  </span>    <span class="kwrd">public</span> <span class="kwrd">class</span> Monitor : IMonitor
   2:      {
<span class="lnum">   3:  </span>        <span class="kwrd">private</span> INotify notify;
   4:  
<span class="lnum">   5:  </span>        [InjectionMethod]
   6:          public void GetNotify(INotify n)
<span class="lnum">   7:  </span>        {
   8:              notify = n;
<span class="lnum">   9:  </span>        }
  10:  
<span class="lnum">  11:  </span>        <span class="kwrd">public</span> <span class="kwrd">void</span> Alarm()
  12:          {
<span class="lnum">  13:  </span>            notify.Send();
  14:          }
<span class="lnum">  15:  </span>    }

在程序运行时,容器会自动实例化GetNotify方法所依赖的对象,并自动调用该方法,将其注入到方法中。

Main函数如下:

<span class="lnum">   1:  </span>        <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
   2:          {
<span class="lnum">   3:  </span>            IUnityContainer container = <span class="kwrd">new</span> UnityContainer();
   4:              container.RegisterType<IMonitor, Monitor>();
<span class="lnum">   5:  </span>            container.RegisterType<INotify, EmailNotify>();
   6:  
<span class="lnum">   7:  </span>            IMonitor monitor = container.Resolve<IMonitor>();
   8:              monitor.Alarm();
<span class="lnum">   9:  </span>
  10:              Console.ReadLine();
<span class="lnum">  11:  </span>        }

运行查看结果:

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐