深入探討WCF緩存機制基本概念
WCF開發工具是一個由微軟公司開發的功能強大的開發插件。它的應用可以幫助我們實現包括在通信方面的各種功能需求。那么接下來,我們將會為大家分析一下其中一個比較基礎的內容,WCF緩存機制的相關概念。#t#
緩存是很占內存的,緩存也有它的好處,這里就WCF緩存機制分析一個案例,希望大家可以從中得到收獲。首先我們看看MSDN中對WCF的Session的說明:它們由調用應用程序顯式啟動和終止。會話期間傳遞的消息按照接收消息的順序進行處理。會話將一組消息相互關聯,從而形成對話。該關聯的含義是抽象的。
例如,一個基于會話的通道可能會根據共享網絡連接來關聯消息,而另一個基于會話的通道可能會根據消息正文中的共享標記來關聯消息。可以從會話派生的功能取決于關聯的性質。不存在與 WCF 會話相關聯的常規數據存儲區。***一句告訴我們,WCF中的Session是無法像Web應用一樣存儲附加信息的。經過研究,我們可以通過擴展MessageHeader實現一個附加的數據存儲區在Client端每次請求Service時發送到Server端。具體實現如下(以前述需求為例)。
這是一個單件類,Client正常登陸得到Server端回傳的UserIdentity實例后可以通過如下代碼將其存入WCF緩存機制:
- UserPermissionInfo.GetInstance().SetUserIdentity
(ServerReturnedUserIdentity);
其中ServerReturnedUserIdentity就是Server產生并回傳的UserIdentity下面我們擴展MessageHeader將我們自己定義的UserIdentity加入進去,WCF緩存代碼如下:
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Text;
- usingSystem.ServiceModel;
- usingSystem.ServiceProcess;
- usingSystem.ServiceModel.Dispatcher;
- usingSystem.ServiceModel.Description;
- usingSystem.ServiceModel.Channels;
- usingSystem.ServiceModel.Configuration;
- namespaceBNCommon.ClientHelper {
- publicclassBNClientMessageInspector:IClientMessageInspector
{ IClientMessageInspector成員- #regionIClientMessageInspector成員
- publicvoidAfterReceiveReply(refMessagereply,objectcorrelationState) { }
- publicobjectBeforeSendRequest(refMessagerequest,IClientChannelchannel) {
- MessageHeaderMessageHeaderMessageHeadermh=MessageHeader.CreateHeader
("UserIdentity","UINS",BNIIClientLayerPlus.UserPermissionInfo
.GetInstance()._UserIdentity);- request.Headers.Add(mh);
- returnnull; }
- #endregion } }
這個類實現了IClientMessageInspector接口,實現該接口可以在Client每次向Server請求前及請求返回后控制Client的行為對發送和接收的數據進行處理。現在我們需要實現BehaviorExtensionElement,IEndpointBehavior將剛剛建立的行為加入Client行為集合,代碼如下:
- usingSystem; usingSystem.Collections.Generic;
- usingSystem.Text; usingSystem.ServiceModel;
- usingSystem.ServiceProcess;
- usingSystem.ServiceModel.Dispatcher;
- usingSystem.ServiceModel.Description;
- usingSystem.ServiceModel.Channels;
- usingSystem.ServiceModel.Configuration;
- namespaceBNCommon.ClientHelper {
- publicclassBNClientEndpointBehavior:BehaviorExtensionElement,
IEndpointBehavior {- IEndpointBehavior成員
- #regionIEndpointBehavior成員
- publicvoidAddBindingParameters(ServiceEndpointendpoint,
BindingParameterCollectionbindingParameters) {}- publicvoidApplyClientBehavior(ServiceEndpointendpoint,
ClientRuntimeclientRuntime) {- clientRuntime.MessageInspectors.Add(newBNClientMessageInspector());
- }
- publicvoidApplyDispatchBehavior(ServiceEndpointendpoint,
EndpointDispatcherendpointDispatcher) { }- publicvoidValidate(ServiceEndpointendpoint)
- { return; }
- #endregion
- publicoverrideTypeBehaviorType {
- get...{
- returntypeof(BNClientEndpointBehavior);
- } }
- protectedoverrideobjectCreateBehavior() {
- returnnewBNClientEndpointBehavior();
- } } }
以上就是對WCF緩存機制的基本介紹。