在上一篇文章中, 我列出了WCF一系列的可扩展对象和元素,并简单介绍了他们各自的功能、适合的场景和具体解决的问题。从本篇开始我将通过一个个具体的例子来介绍如何利用这些扩展点对WCF进行扩展,从而解决一些我们在实现的项目开发中可能出现的问题。
今天,我们将讨论如何通过WCF extension实现多语言、本地化的功能。我们模拟这样的一个场景:我们现在有一个支持多语言的项目,假设通过支持英文(en-US)和简体中文(zh-CN)。我们需要创建一个service为整个系统提供message。对于这个message service,简单起见,我们将基于不同的culture的message存储于不同的Resource文件中,客户端通过访问service来获取基于它自己本地culture的message。比如,如果某一个客户端当前的 culture是en-US,那么会得到英文的message,如果是zh-CN将会得到简体中文的message。
我们很多人会说,在获取message的时候将client端本地的culture作为API的参数传递到service端,service再根据相应的culture从对应的resource文件中获取message不就可以了吗?这样做不是不可以,但是不过优雅。从业务逻辑和非业务逻辑的分离来讲是不是一个好的解决方案,因为从某种意义上讲,culture信息是业务无关的,不适合作为API的一部分,API应该只和具体的业务逻辑相关联。
今天给出的解决方式基于这样的实现原理:在Client端,当调用我们的message service的时候,当前culture被自动放到message header里传到service端;在service端,该culture 信息自动地被取出,并将service端的当前线程的UI culture设置成该值,那么service只需要根据当前线程的culture去取message就可以了。此外考虑到我们改变线程culture可能带来的不可预知的影响,在方法执行完毕将culture重置。
在这里我们先来实现service端的功能:如何从message header中取出culture,并设置当前线程culture。至于Client端的实现,我们将在另一个场景中进行单独介绍。
如何看过前一篇文章的朋友,也许会记得,在列出的8大dispatching system可扩展对象中,有一个对象很适合我们今天的多语言的场景:CallContextInitializer。顾名思义,CallContext表示基于当前线程的关于Call stack的上下文信息,这样的信息本存放在TLS(Thread Local Storage)中。CallContextInitializer就是用于去初始化这些context的。实际上,除了call context的初始化工作之外,CallContextInitializer还可以用于call context的清理工作。
一、Message Service
在正式介绍CallContextInitializer之前,我们闲来介绍一下我们的message service。对于message service的模拟,我们仍然采用我们传统的4层结构:Contract、Service、Hosting和Client。对于Contract,仅仅是下面一个简单的interface:
1: namespace Artech.Messages.Contract
2: {
3: [ServiceContract]
4: public interface IMessage
5: {
6: [OperationContract]
7: string GetMessage();
8: }
9: }
Service的代码很简单,仅仅是以强类型的方式获取该resource item而已:
1: namespace Artech.Messages.Service
2: {
3: public class MessageService:IMessage
4: {
5: public string GetMessage()
6: {
7: return Resources.HelloWorld;
8: }
9: }
10: }
下面是Hosting的Code和configuraion:
1: namespace Artech.Messages.Hosting
2: {
3: public class Program
4: {
5: public static void Main()
6: {
7: using (ServiceHost host = new ServiceHost(typeof(MessageService)))
8: {
9: host.Opened += delegate
10: {
11: Console.WriteLine("Message service has been started up!");
12: };
13:
14: host.Open();
15:
16: Console.Read();
17: }
18: }
19: }
20: }
1: <configuration>
2: <system.serviceModel>
3: <services>
4: <service name="Artech.Messages.Service.MessageService">
5: <endpoint binding="basicHttpBinding" contract="Artech.Messages.Contract.IMessage" />
6: <host>
7: <baseAddresses>
8: <add baseAddress="http://127.0.0.1/messageservice" />
9: </baseAddresses>
10: </host>
11: </service>
12: </services>
13: </system.serviceModel>
14: </configuration>
这是Client端的Configuration:
1: <configuration>
2: <system.serviceModel>
3: <client>
4: <endpoint address="http://127.0.0.1/messageservice" binding="basicHttpBinding"
5: contract="Artech.Messages.Contract.IMessage" name="messageservice" />
6: </client>
7: </system.serviceModel>
8: </configuration>
以及Client端的Code:
1: namespace Artech.Messages.Client
2: {
3: class Program
4: {
5: private const string CultureInfoHeadLocalName = "__CultureInfo";
6: private const string CultyreInfoHeaderNamespace = "urn:artech.com";
7:
8: static void Main(string[] args)
9: {
10: using (ChannelFactory<IMessage> channelFactory = new ChannelFactory<IMessage>("messageservice"))
11: {
12: IMessage proxy = channelFactory.CreateChannel();
13: using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
14: {
15: MessageHeader<CultureInfo> header = new MessageHeader<CultureInfo>(Thread.CurrentThread.CurrentUICulture);
16: OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader(CultureInfoHeadLocalName,CultyreInfoHeaderNamespace));
17: Console.WriteLine("The UI culture of current thread is {0}", Thread.CurrentThread.CurrentUICulture);
18: Console.WriteLine(proxy.GetMessage());
19: }
20:
21: Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-CN");
22: using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
23: {
24: MessageHeader<CultureInfo> header = new MessageHeader<CultureInfo>(Thread.CurrentThread.CurrentUICulture);
25: OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader(CultureInfoHeadLocalName, CultyreInfoHeaderNamespace));
26: Console.WriteLine("The UI culture of current thread is {0}", Thread.CurrentThread.CurrentUICulture);
27: Console.WriteLine(proxy.GetMessage());
28: }
29: }
30:
31: Console.Read();
32: }
33: }
34: }
在这里做一些简单的介绍:通过ChannelFactory创建Channel(proxy)对象,利用此Channel(proxy)创建OperationContextScope(OperationContextScope和OperationContext的关系就如同TransactionScope和Transaction的关系一样,相当于定义OperationContext的作用范围)。在此OperationContextScope作用范围内创建MessageHeader,内容为当前线程的UICulture,Localname和Namespace为定义的常量。将message header放到OutgoingMessageHeaders集合中,通过proxy对象调用message service获得对应的service,由于第一次调用使用的是默认的culture(en-US),我们希望返回的结果是英文,而第二次service invocation的culture为zh-CN,所以我们希望返回的结果是中文。
二、创建CallContextInitializer
为了实现Localization,我们先创建一个CallContextInitializer,我们姑且叫它CultureSettingCallContextInitializer。所有的CallContextInitializer都实现接口:System.ServiceModel.Dispatcher.ICallContextInitializer。
1: public interface ICallContextInitializer
2: {
3: void AfterInvoke(object correlationState);
4: object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message);
5: }
该结构定义了两个方法:BeforeInvoke和AfterInvoke,允许你在真正的service方法执行前和执行后对CallContext进行初始化和清理。如何你希望在BeforeInvoke创建的对象能够被AfterInvoke,你可以将该对象作为BeforeInvoke 的返回值,在执行AfterInvoke的时候,该值将作为其中的参数。
这是CultureSettingCallContextInitializer的定义:
1: namespace Artech.CallContextInitializers
2: {
3: public class CultureSettingCallContextInitializer:ICallContextInitializer
4: {
5: private const string CultureInfoHeadLocalName = "__CultureInfo";
6: private const string CultyreInfoHeaderNamespace = "urn:artech.com";
7: public void AfterInvoke(object correlationState)
8: {
9: CultureInfo[] currentCulture = correlationState as CultureInfo[];
10: Thread.CurrentThread.CurrentCulture = currentCulture[0];
11: Thread.CurrentThread.CurrentUICulture = currentCulture[1];
12: }
13:
14: public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
15: {
16: CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
17: CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;
18:
19: if (message.Headers.FindHeader(CultureInfoHeadLocalName, CultyreInfoHeaderNamespace) > -1)
20: {
21: CultureInfo cultureInfo = message.Headers.GetHeader<CultureInfo>(CultureInfoHeadLocalName, CultyreInfoHeaderNamespace);
22: Thread.CurrentThread.CurrentCulture = cultureInfo;
23: Thread.CurrentThread.CurrentUICulture = cultureInfo;
24: }
25:
26: return new CultureInfo[] { currentCulture, currentUICulture };
27: }
28: }
29: }
由于我们只想改变执行service方法过程中线程的culture,所以我们在BeforeInvoke中先通过一个Array将CurrentCulture和CurrentUICulture保存起来,然后根据message header的local name和namespace将client端传入的culture获取出来,将此值设置到当前线程。最有返回保存有原来CurrentCulture和CurrentUICulture的Array。在AfterInvoke中通过correlationState参数将这个Array取出,重置CurrentCulture和CurrentUICulture。
三、通过OperationBehavior应用CallContextInitializer
由于CallContextInitializer是DispatchOperation的属性,DispatchOperation又可以通过DispatchRuntime的Operations集合中获得。所以我们可以有两个方式将我们创建的CultureSettingCallContextInitializer应用到Dispatching system中。一是通过OperationBehavior,而是通过EndpointBehavior。
我们现在介绍OperationBehavior的解决方案,由于OperationBehavior是通过Attribute的形式被使用,所以我们的将OperationBehavior定义成继承Attribute的class:CultureSettingBehaviorAttribute。
1: namespace Artech.CallContextInitializers
2: {
3: public class CultureSettingBehaviorAttribute:Attribute,IOperationBehavior
4: {
5: public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters){}
6: public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation){}
7: public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
8: {
9: dispatchOperation.CallContextInitializers.Add(new CultureSettingCallContextInitializer());
10: }
11: public void Validate(OperationDescription operationDescription){}
12: }
13: }
实际上只有一句有意思的代码,将CultureSettingCallContextInitializer对象设置到应用了OperationBehavior
对应的DispatchOperation对象上1: dispatchOperation.CallContextInitializers.Add(new CultureSettingCallContextInitializer());
那么我们就可以将此CultureSettingBehaviorAttribute直接应用到Contract的Operation上、或者Service的对应的method上。比如我们应用到Contract的GetMessage上,那么它将影响到所有实现了该contract的所有service。
1: {
2: [ServiceContract]
3: public interface IMessage
4: {
5: [OperationContract]
6: [CultureSettingBehavior]
7: string GetMessage();
8: }
9: }
这时候我们运行程序,将会得到如何的输出:
四、通过EndpointBehavior运用CallContextInitializer
我们接着来讨论另一种运用CallContextInitializer的方式:通过EndpointBehavior。为此u,我们创建了我们的EndpointBehavior:CultureSettingBehavior。
1: namespace Artech.CallContextInitializers
2: {
3: public class CultureSettingBehavior: IEndpointBehavior
4: {
5: public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters){}
6:
7: public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime){}
8:
9: public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
10: {
11: foreach (var operation in endpointDispatcher.DispatchRuntime.Operations)
12: {
13: operation.CallContextInitializers.Add(new CultureSettingCallContextInitializer());
14: }
15: }
16:
17: public void Validate(ServiceEndpoint endpoint){}
18: }
19: }
有效的代码也是在ApplyDispatchBehavior中,我们通过遍历endpointDispatcher.DispatchRuntime.Operations集合,将每个DispatchOperation的CallContextInitializers中加上我们的CultureSettingCallContextInitializer对象。 EndpointBehavior只能通过Configuration的方式使用,我们还需要为此创建一个BehaviorExtensionElement:CultureSettingBehaviorElement。
1: namespace Artech.CallContextInitializers
2: {
3: public class CultureSettingBehaviorElement: BehaviorExtensionElement
4: {
5: public override Type BehaviorType
6: {
7: get
8: {
9: return typeof(CultureSettingBehavior);
10: }
11: }
12:
13: protected override object CreateBehavior()
14: {
15: return new CultureSettingBehavior();
16: }
17: }
18: }
那么我们就可以根据配置文件来应用我们的自定义的EndpointBehavior了:
1: <configuration>
2: <system.serviceModel>
3: <behaviors>
4: <endpointBehaviors>
5: <behavior name="cultureSettingBehavior">
6: <cultureSettingElement />
7: </behavior>
8: </endpointBehaviors>
9: </behaviors>
10: <extensions>
11: <behaviorExtensions>
12: <add name="cultureSettingElement" type="Artech.CallContextInitializers.CultureSettingBehaviorElement, Artech.CallContextInitializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
13: </behaviorExtensions>
14: </extensions>
15: <services>
16: <service name="Artech.Messages.Service.MessageService">
17: <endpoint behaviorConfiguration="cultureSettingBehavior" binding="basicHttpBinding"
18: contract="Artech.Messages.Contract.IMessage" />
19: <host>
20: <baseAddresses>
21: <add baseAddress="http://127.0.0.1/messageservice" />
22: </baseAddresses>
23: </host>
24: </service>
25: </services>
26: </system.serviceModel>
27: </configuration>
在contract中,将CultureSettingBehaviorAttribute去掉,我们一样可以得到同上面一样的输出结果。
WCF后续之旅:
WCF后续之旅(1): WCF是如何通过Binding进行通信的
WCF后续之旅(2): 如何对Channel Layer进行扩展——创建自定义Channel
WCF后续之旅(3): WCF Service Mode Layer 的中枢—Dispatcher
WCF后续之旅(4):WCF Extension Point 概览
WCF后续之旅(5): 通过WCF Extension实现Localization
WCF后续之旅(6): 通过WCF Extension实现Context信息的传递
WCF后续之旅(7):通过WCF Extension实现和Enterprise Library Unity Container的集成
WCF后续之旅(8):通过WCF Extension 实现与MS Enterprise Library Policy Injection Application Block 的集成
WCF后续之旅(9):通过WCF的双向通信实现Session管理[Part I]
WCF后续之旅(9): 通过WCF双向通信实现Session管理[Part II]
WCF后续之旅(10): 通过WCF Extension实现以对象池的方式创建Service Instance
WCF后续之旅(11): 关于并发、回调的线程关联性(Thread Affinity)
WCF后续之旅(12): 线程关联性(Thread Affinity)对WCF并发访问的影响
WCF后续之旅(13): 创建一个简单的WCF SOAP Message拦截、转发工具[上篇]
WCF后续之旅(13):创建一个简单的SOAP Message拦截、转发工具[下篇]
WCF后续之旅(14):TCP端口共享
WCF后续之旅(15): 逻辑地址和物理地址
WCF后续之旅(16): 消息是如何分发到Endpoint的--消息筛选(Message Filter)
WCF后续之旅(17):通过tcpTracer进行消息的路由