Unity学习笔记(1)

     Unity是微软企业库4.0加入的一个Ioc容器,具体介绍可以访问相关网站(codeplex、MSDN),这里制作简单说明。

    The Unity Application Block (Unity) 是一个轻量级, 可扩展的DI(dependency injection)容器,支持构造器注入,属性注入和 method call injection. 主要提供如下的好处:

  • 提供使用简单的代码进行简化对象创建,尤其是层次对象结构和相互依赖的对象
  • 支持abstraction of requirements;这个特点允许开发者在运行时或在配置文件中制定依赖关系,并且简化管理交叉忧虑(crosscutting concerns).
  • 它可以通过延迟容器中的组件构建来增加弹性。
  • 它还有服务本地能力 ,可以允许用户存储或缓存容器。这个特性对ASP.NET Web applications特别有用,开发者可以 在session 或 application保持容器。

     至于三个模式,这里不做详细描述Inversion of Control (IoC) patternDependency Injection (DI) patternInterception pattern

    Unity支持container-configured injection, constructor injection, property injection, and method call injection。

    Unity Application Block暴露两个方法用来通过容器注册和映射:

  • RegisterType. 这个方法注册一类型到容器。在适当的时候,容器构建一个你指定类型的实例。 This could be in response to dependency injection initiated through class attributes or when you call the Resolve method. 对象的生命周期由参数指定.如果没有指定,类型将拥有一个短暂的生命周期。容器将在每次调用Resolve时创建一个新的实例。
  • RegisterInstance.这个方法向容器中注册一个自己制定的类型的已存在的实例,其生命周期有你自己制定。 在生命周期内容器返回一个已经存在的实例。如果你没有指定一个生命周期,实例由容器来控制生命周期。

Container-Configured Registration of Types

下面的例子通过重载RegisterTypeResolve方法注册一个IMyService接口的映射,指定容器返回一个CustomerService类(实现IMyService接口)的实例

1 IUnityContainer myContainer  =   new  UnityContainer();
2 myContainer.RegisterType < IMyService, CustomerService > ();
3 IMyService myServiceInstance  =  myContainer.Resolve < IMyService > ();

Container-Configured Registration of Existing Object Instances

Code

Constructor Injection
构造函数依赖注入,当通过 Resolve 方法 调用容器的时候,容器自动创建该类构造函数中参数依赖的类的实例。例如在接下来的代码中CustomerService类依赖LoggingService.(类依赖的关系可以参考OOAD或UML书籍)。

1 public   class  CustomerService
2 {
3  public CustomerService(LoggingService myServiceInstance)
4  
5    // work with the dependent instance
6    myServiceInstance.WriteToLog("SomeValue");
7  }

8}

调用

1 IUnityContainer uContainer  =   new  UnityContainer();
2 CustomerService myInstance  =  uContainer.Resolve < CustomerService > ();

Property (Setter) Injection
接下来的代码说明属性注入. ProductService 类暴露一个使用另一个类SupplierData实例的属性,使用Dependency attribute标注该属性.

 1 public   class  ProductService
 2 {
 3  private SupplierData supplier;
 4
 5  [Dependency]
 6  public SupplierData SupplierDetails 
 7  {
 8    get return supplier; }
 9    set { supplier = value; }
10  }

11}

创建ProductService类实例的时候,Unity Application Block自动生成一个SupplierData类的实例并且 and sets it as the value of the SupplierDetails property of the ProductService class.

你可能感兴趣的:(unity)