Unity3.0基于约定的自动注册机制

前文《Unity2.0容器自动注册机制》中,介绍了如何在 Unity 2.0 版本中使用 Auto Registration 自动注册机制。在 Unity 3.0 版本中(2013年),新增了基于约定的自动注册机制(Registration By Convention),以使 Unity 容器的装配过程变得更加简单,并且减少冗余代码。

Convention over Configuration

Convention over Configuration 是现如今非常流行的设计风格,很多框架都在尝试采纳该风格,包括 ASP.NET MVC。简要的说就是需要依赖某种预先定义的约定,类似于文件、目录的命名,类或者系统依据约定做指定的事等。例如,在 ASP.NET MVC 中,所有 Controller 都必须包含 “Controller” 后缀,这样框架才能找到该 Controller 并进行初始化。

约定风格使开发人员的生活变得轻松多了,我们无需再耗费精力在繁杂的配置上,转而采用一些简单的约定规则。

例如,有一个时常出现的模式。我们定义一个类 Foo 来作为接口 IFoo 的默认实现。在匈牙利命名法的编程风格中,标记 “I” 通常是接口的第一个字母。利用这一点,我们可以设定一个命名约定。

1   public interface IConvention
2   {
3   }
4 
5   public class Convention : IConvention
6   {
7   }

基于此约定,我们可以扫描整个程序集来查找满足约定的接口和类,并自动注册进 Unity 容器。

Registration by Convention

早在2009年,Jeremy Miller 在 StructureMap 2.5 版本中即已引入了基于约定的自动注册机制,通过拥抱 Convention over Configuration 设计范式来降低使用 Configuration 的开销。

同年,Derek Greer 为 Unity 2.0 增加了 Convention-based Registration Extension 扩展。而微软官方直到2013年 Unity 3.0 才增加此功能。

基于约定的自动注册机制目的在于简化类型注册过程,减少类型注册代码。比起无数的 “container.RegisterType<IFoo, Foo>()”,可以直接通过扫描程序集,依据一些既定的规则来自动完成类型注册。

1       using (var container = new UnityContainer())
2       {
3         container.RegisterTypes(
4            AllClasses.FromAssembliesInBasePath(),
5            WithMappings.FromMatchingInterface,
6            WithName.Default,
7            WithLifetime.ContainerControlled);
8       }

支持的 Conventions

Convention 必须指明哪些可用类型应该被映射进 Unity 容器中。当前的 Unity 3.0 中的可用约定支持如下规则:

  1. 识别扫描被注册类型所在的程序集:可以使用提供的程序集列表,使用当前已加载的程序集列表,使用在当前应用程序目录中的所有程序集列表。可以进一步通过类型的名称、后缀或者其他规则进行过滤,并且支持 LINQ 语法。这一步准备了可能被注册的类型列表。默认情况下,所有系统程序集将被自动过滤掉。当然,也不是非要使用帮助类中所提供的类型加载方式,可以使用一个方法来获取类型的枚举集合,或者甚至直接使用一个数组。
  2. 可选项,指定哪些类型(典型的是接口或者抽象类)需要通过容器来映射到步骤 1 中的类型。目前的约定包括:
    • 映射哪些遵循命名约定的类型。例如类 Foo 和 接口 IFoo 。
    • 映射类型实现的所有接口。
    • 映射类型实现的所有接口,并且这些接口必须与类型定义在同一程序集内。
  3. 可选项,指定是否使用命名注册(Named Registration)。也可以使用类型的名称作为注册名称。
  4. 可选项,指定注册类型时使用哪种生命周期管理器(Lifetime Manager)。
  5. 可选项,确定是否有类型成员需要注入(Injected Parameter)。

所有约定通过 RegisterTypes 方法来表述:

1 public static IUnityContainer RegisterTypes(
2     this IUnityContainer container, 
3     IEnumerable<Type> types, 
4     Func<Type, IEnumerable<Type>> getFromTypes = null, 
5     Func<Type, string> getName = null, 
6     Func<Type, LifetimeManager> getLifetimeManager = null, 
7     Func<Type, IEnumerable<InjectionMember>> getInjectionMembers = null, 
8     bool overwriteExistingMappings = false);

RegisterTypes 方法签名描述:

Parameter

Description

Types

This parameter is an enumerable collection of types that you want to register with the container. These are the types that you want to register directly or create mappings to. You can create this collection by providing a list of types directly or by using one of the methods of the built-in AllClasses helper class: for example, the method FromLoadedAssemblies loads all of the available types from the currently loaded assemblies.

You can use LINQ to filter this enumeration.

getFromTypes

This optional parameter identifies the types you want to map from in the container. The built-in WithMappings helper class provides several options for this mapping strategy: for example, theMatchingInterface property creates mappings where there are interfaces and implementations that follow the naming conventionITenant and Tenant.

getName

This optional parameter enables you to control whether to create default registrations or named registrations for the types. The built-in helper class WithName, enables you to choose between using default registrations or named registrations that use the type name.

getLifeTimeManager

This optional parameter enables you to select from the built-in lifetime managers.

getInjectionMembers

This optional parameter enables you to provide definitions for any injection members for the types that you are registering.

overwriteExistingMappings

This optional parameter enables you to control how the method behaves if it detects an attempt to overwrite an existing mapping in the Unity container. By default, the RegisterTypes method throws an exception if it detects such an attempt. If this parameter is true, the method silently overwrites an existing mapping with a new one based on the values of the other parameters.

简单示例:

 1       var container = new UnityContainer();
 2 
 3       container.AddNewExtension<Interception>();
 4       container.RegisterTypes(
 5         AllClasses.FromLoadedAssemblies().Where(
 6           t => t.Namespace == "OtherUnitySamples"),
 7         WithMappings.FromMatchingInterface,
 8         getInjectionMembers: t => new InjectionMember[]
 9         {
10           new Interceptor<VirtualMethodInterceptor>(),
11           new InterceptionBehavior<LoggingInterceptionBehavior>()
12         });

自定义约定类

Unity 通过提供注册约定抽象类 RegistrationConvention 来提供扩展性。

1   public abstract class RegistrationConvention
2   {
3     public abstract Func<Type, IEnumerable<Type>> GetFromTypes();
4     public abstract Func<Type, IEnumerable<InjectionMember>> GetInjectionMembers();
5     public abstract Func<Type, LifetimeManager> GetLifetimeManager();
6     public abstract Func<Type, string> GetName();
7     public abstract IEnumerable<Type> GetTypes();
8   }

我们可以自定义实现 RegistrationConvention :

 1   class CustomizedConvention : RegistrationConvention
 2   {
 3     public override Func<Type, IEnumerable<Type>> GetFromTypes()
 4     {
 5       return t => t.GetInterfaces();
 6     }
 7 
 8     public override Func<Type, IEnumerable<InjectionMember>> GetInjectionMembers()
 9     {
10       return null;
11     }
12 
13     public override Func<Type, LifetimeManager> GetLifetimeManager()
14     {
15       return t => new ContainerControlledLifetimeManager();
16     }
17 
18     public override Func<Type, string> GetName()
19     {
20       return t => t.Name;
21     }
22 
23     public override IEnumerable<Type> GetTypes()
24     {
25       yield return typeof(Foo);
26       yield return typeof(Bar);
27     }
28   }
1       var container = new UnityContainer();
2       container.RegisterTypes(new CustomizedConvention());

显示已注册类型信息

可以通过显示枚举容器的 Registrations 属性来获得所有的注册信息。

 1   class Program
 2   {
 3     static void Main(string[] args)
 4     {
 5       var container = new UnityContainer();
 6       container.RegisterTypes(new CustomizedConvention());
 7 
 8       Console.WriteLine("Container has {0} Registrations:",
 9         container.Registrations.Count());
10       foreach (ContainerRegistration item in container.Registrations)
11       {
12         Console.WriteLine(item.GetMappingAsString());
13       }
14 
15       Console.ReadKey();
16     }
17   }
18 
19   public interface IFoo { }
20   public class Foo : IFoo { }
21   public interface IBar { }
22   public class Bar : IBar { }
23 
24   static class ContainerRegistrationsExtension
25   {
26     public static string GetMappingAsString(
27       this ContainerRegistration registration)
28     {
29       string regName, regType, mapTo, lifetime;
30 
31       var r = registration.RegisteredType;
32       regType = r.Name + GetGenericArgumentsList(r);
33 
34       var m = registration.MappedToType;
35       mapTo = m.Name + GetGenericArgumentsList(m);
36 
37       regName = registration.Name ?? "[default]";
38 
39       lifetime = registration.LifetimeManagerType.Name;
40       if (mapTo != regType)
41       {
42         mapTo = " -> " + mapTo;
43       }
44       else
45       {
46         mapTo = string.Empty;
47       }
48       lifetime = lifetime.Substring(
49         0, lifetime.Length - "LifetimeManager".Length);
50       return String.Format(
51         "+ {0}{1}  '{2}'  {3}", regType, mapTo, regName, lifetime);
52     }
53 
54     private static string GetGenericArgumentsList(Type type)
55     {
56       if (type.GetGenericArguments().Length == 0) return string.Empty;
57       string arglist = string.Empty;
58       bool first = true;
59       foreach (Type t in type.GetGenericArguments())
60       {
61         arglist += first ? t.Name : ", " + t.Name;
62         first = false;
63         if (t.GetGenericArguments().Length > 0)
64         {
65           arglist += GetGenericArgumentsList(t);
66         }
67       }
68       return "<" + arglist + ">";
69     }
70   }

输出结果:

参考资料

 

posted @ 2013-11-13 08:24  sangmado  阅读(2763)  评论(7编辑  收藏  举报