WCF服務實例管理模式之PreSession應用
作者:佚名
WCF服務實例管理模式中的PreSession模式的應用,需要我們將其綁定到一個支持Swssion的Binding對象。在這里將會給出具體的操作方法。
在WCF服務實例管理模式中,總共有三種應用模式可以供開發人員選擇應用。今天主要就是針對其中一個比較常用的PreSession模式進行一些相關介紹。PreSession 模式需要綁定到支持 Session 的 Binding 對象。
在客戶端代理觸發終止操作前,WCF 為每個客戶端維持同一個服務對象,因此 PreSession 模式可用來保持調用狀態。也正因為如此,PreSession 在大并發服務上使用時要非常小心,避免造成服務器過度負擔。雖然支持 Session 的 Binding 對象缺省就會啟用 PreSession 模式,但依然建議你強制指定 SessionMode.Required 和 InstanceContextMode.PerSession。
- [ServiceContract(SessionMode = SessionMode.Required)]
- public interface IMyService
- {
- [OperationContract]
- void Test();
- }
- [ServiceBehavior(InstanceContextMode =
InstanceContextMode.PerSession)]- public class MyServie : IMyService, IDisposable
- {
- public MyServie()
- {
- Console.WriteLine("Constructor:{0}", this.GetHashCode());
- }
- [OperationBehavior]
- public void Test()
- {
- Console.WriteLine("Test:{0}", OperationContext.Current.SessionId);
- }
- public void Dispose()
- {
- Console.WriteLine("Dispose");
- }
- }
- public class WcfTest
- {
- public static void Test()
- {
- AppDomain.CreateDomain("Server").DoCallBack(delegate
- {
- ServiceHost host = new ServiceHost(typeof(MyServie),
new Uri("http://localhost:8080/MyService"));- host.AddServiceEndpoint(typeof(IMyService),
new WSHttpBinding(), "");- host.Open();
- });
- //-----------------------
- IMyService channel = ChannelFactory<IMyService>.
CreateChannel(new WSHttpBinding(),- new EndpointAddress("http://localhost:8080/MyService"));
- using (channel as IDisposable)
- {
- channel.Test();
- channel.Test();
- }
- }
- }
輸出:
- Constructor:30136159
- Test:urn:uuid:2f01b61d-40c6-4f1b-a4d6-4f4bc3e8847a
- Test:urn:uuid:2f01b61d-40c6-4f1b-a4d6-4f4bc3e8847a
- Dispose
【編輯推薦】
責任編輯:曹凱
來源:
豆豆網




















