松耦合、高内聚是我们进行设计的永恒的目标,如何实现这样的目标呢?我们有很多实现的方式和方法,不管这些方式和方法在表现形式上有什么不同,他们的思想都可以表示为:根据稳定性进行关注点的分离或者分解,交互双方依赖于一个稳定的契约,而降低对对方非稳定性因素的依赖。从抽象和稳定性的关系来讲,抽象的程度和稳定程度成正相关关系。由此才有了我们面向抽象编程的说法,所以“只有依赖于不变,才能应万变”。
然后,对于面向对象的思想来讲,我们的功能通过一个个具体的对象来承载。对象是具体的,不是抽象的;创建对象是必然的;对象的创建从某种程度上即使对面向抽象的违背。所以模块之间的耦合度在很大程度上是由于对象创建的方式决定的,而在对象创建过程实现解耦是实现我们“松耦合、高内聚”目标的一个重要途径。对于这一点,我们可以看看我们常用的设计模式中有多少是用于解决如何合理进行对象创建的就可以知道了。Enterprise Library推出的新的Application Block:Unity Application Block为我们提供了一个很好的、可扩展的框架,帮助我们合理、有效的创建对象,并解决创建对象中的依赖。而通过WCF一个简单的扩展对象,就可以很容易地实现和Unity的集成。
由于本篇文章的重点仍然是对WCF的扩展,因此我不会花太多的篇幅对Enterprise Library Unity作详细的介绍。这是比较官方的定义:"The Unity Application Block (Unity) is a lightweight, extensible dependency injection container with support for constructor, property, and method call injection”. Unity实际是建立在ObjectBuilder基础之上,而ObjectBuilder是整个Enterprise Library的基石(实际上还不止于此,MS P&P开发的很多的开源框架都依赖于ObjectBuilder,比如CAB、SCSF等),为我们提供了一个可扩展的、基于策略(strategy based)对象创建方式。借助于ObjectBuilder,Unity可以帮助我们基于Interface或者abstract class创建对象;可以帮助我们管理对象的生命周期;以及实现依赖注入(DI:Dependency Injection)。下面是3种主要的DI方式:
- Constructor Injection:帮助我们选择我们需要的构造函数来创建对象。
- Property (Setter) Injection:帮助我们在创建的对象上自动设置某些必要的属性值。
- Method Injection:帮助我们在对象上调用我们指定的方法做一些初始化的工作。
如果读者想进一步了解Unity Application Block和Enterprise Library,可以访问微软P&P 的网站。
二、实现基于Unity的IntanceProvider
在本系列的第三部分对Dispachter的介绍,和第四部分对WCF可扩展点的介绍中,我提到了一个重要的对象InstanceProvider, 该对象用于service instance的创建。既然Unity的根本目的是创建对象,我们就可以自定义InstanceProvider,让Unity来帮助创建service instance,很容易地实现了和Unity的集成。
下面是我们的自定义InstanceProvider:UnityInstanceProvider
namespace Artech.WCFExtensions
2: {
class UnityInstanceProvider: IInstanceProvider
4: {
private Type _contractType;
string _containerName;
7:
string containerName)
9: {
null)
11: {
);
13: }
14:
this._containerName = containerName;
this._contractType = contractType;
17: }
18:
#region IInstanceProvider Members
20:
object GetInstance(InstanceContext instanceContext, Message message)
22: {
as UnityConfigurationSection;
null)
25: {
string.Format(CultureInfo.CurrentCulture, Resources.MissUnityConfiguration));
27: }
28:
new UnityContainer();
30: UnityContainerElement containerElement;
this._containerName))
32: {
33: containerElement = unitySection.Containers.Default;
34: }
else
36: {
this._containerName];
38: }
39: containerElement.Configure(container);
as UnityTypeElement[];
41: containerElement.Types.CopyTo(unityTypeElements, 0);
42:
this._contractType).Count() == 0)
44: {
this._contractType, instanceContext.Host.Description.ServiceType);
46: }
47:
this._contractType);
49: }
50:
object GetInstance(InstanceContext instanceContext)
52: {
null);
54: }
55:
object instance)
57: {
as IDisposable;
null)
60: {
61: disposable.Dispose();
62: }
63: }
64:
#endregion
66: }
67: }
68:
我们来简单讨论一下上面的逻辑。首先Unity常用的做法就根据Interface或者abstract class来进行对象的创建,从而实现对抽象的依赖,而Interface或者abstract class和concrete type之间的mapping关系可以通过配置或者代码注册。对于service instace来说,这个Interface就是ServiceContract。而Unity通过一个叫做UnityContainer对象创建具体的对象和进行生命周期的管理,Container是一个囊括了所有对象创建和生命周期管理所需资源的容器。这些资源包括:Interface或者abstract class和concrete type之间的mapping关系;Dependency Injection的定义;Extensions等等。UnityContainer之间可以嵌套从而形成一个树状结构,我们可以通过一个ID来定位我们需要的container。所以我们定义了两个field:_contractType和_containerName。
private Type _contractType;
string _containerName;
GetInstance方式提供了service instance创建的实现。具体是这样做的:
as UnityConfigurationSection;
null)
3: {
string.Format(CultureInfo.CurrentCulture, Resources.MissUnityConfiguration));
5: }
在配置文件中找到unity的配置,如何没有找到抛出ConfigurationErrorsException异常。
new UnityContainer();
2: UnityContainerElement containerElement;
this._containerName))
4: {
5: containerElement = unitySection.Containers.Default;
6: }
else
8: {
this._containerName];
10: }
11: containerElement.Configure(container);
12:
然后创建UnityContainer对象,然后通过配置的信息对我们创建的UnityContainer进行配置。如何我们没有制定container name,使用默认的配置节,否则使用container name制定的配置节。
as UnityTypeElement[];
2: containerElement.Types.CopyTo(unityTypeElements, 0);
3:
this._contractType).Count() == 0)
5: {
this._contractType, instanceContext.Host.Description.ServiceType);
7: }
因为很有可能在unity的配置中,并没有ServiceContract type对应的配置项,在这种情况下,我将自动注册ServiceContract 和ServiceType的匹配关系,ServiceType通过instanceContext.Host.Description.ServiceType获得。
最后通过UnityContainer的Resolve创建service instance。
this._contractType);
三、创建UnityInstanceProvider对应的Behavior
InstanceProvider可以通过ContractBehavior来指定,也可以通过EndpointBehavior来指定,我们首先创建ContractBehavior:UnityBehaviorAttribute。由于ContractBehavior通过Custom Attribute的形式指定,所以UnityBehaviorAttribute是一个attribute.
namespace Artech.WCFExtensions
2: {
class UnityBehaviorAttribute:Attribute, IContractBehavior
4: {
string ContainerName
6: { get; set; }
7:
#region IContractBehavior Members
9:
void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
11: {}
12:
void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
14: {}
15:
void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
17: {
this.ContainerName);
19: }
20:
void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
22: {}
23:
#endregion
25: }
26: }
27:
需要做的仅仅是在ApplyDispatchBehavior中,将当前的DispatchRuntime的InstanceProvider 指定成我们的UnityInstanceProvider。
我们再定义一下EndpointBehavior:UnityBehavior。
namespace Artech.WCFExtensions
2: {
class UnityBehavior: IEndpointBehavior
4: {
string _containerName;
6:
string containerName)
8: {
this._containerName = containerName;
10: }
11:
#region IEndpointBehavior Members
13:
void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
15: {}
16:
void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
18: {}
19:
void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
21: {
this._containerName);
23: }
24:
void Validate(ServiceEndpoint endpoint)
26: {}
27:
#endregion
29: }
30: }
31:
在ApplyDispatchBehavior,通过endpointDispatcher.DispatchRuntime获得当前的DispatchRuntime对象,并将InstanceProvider我们的UnityInstanceProvider。
最后为了UnityBehavior定义BehaviorExtensionElement:
namespace Artech.WCFExtensions
2: {
class UnityBehaviorElement: BehaviorExtensionElement
4: {
)]
string ContainerName
7: {
8: get
9: {
string;
11: }
12: set
13: {
value;
15: }
16: }
17:
override Type BehaviorType
19: {
20: get
21: {
typeof(UnityBehavior);
23: }
24: }
25:
object CreateBehavior()
27: {
this.ContainerName);
29: }
30: }
31: }
32:
添加一个ContainerName的配置项,在配置文件中指定。
四、应用我们的UnityInstanceProvider
我们现在将我们上面所做的所有工作应用到具体的WCF调用场景中。为此我们创建了一个MessageService的例子(根据Message的Key的Culture返回具体的message的内容),这个例子在本系列第五部分中介绍通过WCF extension实现Localization中介绍过。
这是我们经典的四层结构:
I、Artech.Messages.Contract:
namespace Artech.Messages.Contract
2: {
3: [ServiceContract]
)]
interface IMessage
6: {
7: [OperationContract]
string key);
9: }
10: }
在IMessage上应用了我们的ContractBehavor:UnityBehavior,同时指定container name为:wcfservice。
II、Artech.Messages.Service
namespace Artech.Messages.Service
2: {
class MessageService:IMessage
4: {
5: [Dependency]
public IMessageManager MessageManager
7: { get; set; }
8:
9: [InjectionMethod]
void Initialize()
11: {
);
);
14: }
15:
#region IMessage Members
17:
string key)
19: {
this.MessageManager.GetMessage(key, Thread.CurrentThread.CurrentUICulture);
21: }
22:
#endregion
24: }
25:
interface IMessageManager
27: {
object[] parameters);
29: }
30:
class MessageManager : IMessageManager
32: {
public ResourceManager ResourceManager
34: { get; set; }
35:
public MessageManager()
37: {
typeof(Resources).Assembly);
39: }
40:
#region IMessageManager Members
42:
object[] parameters)
44: {
string message = ResourceManager.GetString(key, culture);
string.Format(culture, message, parameters);
47: }
48:
#endregion
50: }
51: }
52:
对于MessageService,需要着重介绍一下。因为使用到了一些Unity的Attribute。首先是MessageManager属性,它是一个Interface,上面标注了[Dependency],表明这是一个依赖属性。仔细看代码,此MessageManager并没有进行赋值的地方,而且此属性直接用在了GetMessage()方法上。实际上,对MessageManager进行初始化就是Unity container为我们实现的,在创建MessageService对象后,Unity container会来本container的范围了找到IMessageManager 找到与之复配的concrete type。
1: [Dependency]
public IMessageManager MessageManager
3: { get; set; }
对于我们创建出来的MessageService的对象,我们希望能够自动调用一些初始化的方法来进行一些初始化的工作,我们可以通过InjectionMethodAttribute来实现。在Initialize,我希望指定当前的culture为简体中文(我当前机器默认为en-US)
1: [InjectionMethod]
void Initialize()
3: {
);
);
6: }
而MessageManager 实现了IMessageManager ,提供了GetMessage的真正实现。Message存储在Resource温家中:
Default:
zh-CN:
III、Artech.Messages.Hosting
>
>
>
/>
>
6:
>
>
>
/>
>
>
/>
>
>
>
>
>
20:
>
>
>
>
/>
>
>
>
>
>
31:
在unity 配置节中,定义了名为wcfservice的container,该名称就是在ServiceContract在UnitBehavior中指定的参数。在该container中定了了IMessageManager和具体的type(MessageManager)之间的匹配。这解决了MessageService中MessageManager属性的实例化的问题。
IV、Artech.Messages.Client
namespace Artech.Messages.Client
2: {
class Program
4: {
string[] args)
6: {
))
8: {
9: IMessage messageProxy = channelFactory.CreateChannel();
));
11: }
12:
13: Console.Read();
14: }
15: }
16: }
17:
messageservice是配置的endpoint的名称。config文件就不列出来了。最后我们运行程序看最终的结果:
V、使用EndpointBehavior
上面我们是通过ContractBeahvior。现在我们将ServiceContract的UnityBehaviorAttribute去掉,在config中运用我们的EndpointBehavior:
>
>
>
/>
>
>
>
>
>
/>
>
>
>
>
>
/>
>
>
>
>
/>
>
>
/>
>
>
>
>
>
>
>
>
>
/>
>
>
>
>
>
41:
我们一样可以得到上面的结果。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。