WCF服務(wù)實(shí)例管理模式之PreSession應(yīng)用
在WCF服務(wù)實(shí)例管理模式中,總共有三種應(yīng)用模式可以供開發(fā)人員選擇應(yīng)用。今天主要就是針對其中一個(gè)比較常用的PreSession模式進(jìn)行一些相關(guān)介紹。PreSession 模式需要綁定到支持 Session 的 Binding 對象。
在客戶端代理觸發(fā)終止操作前,WCF 為每個(gè)客戶端維持同一個(gè)服務(wù)對象,因此 PreSession 模式可用來保持調(diào)用狀態(tài)。也正因?yàn)槿绱?,PreSession 在大并發(fā)服務(wù)上使用時(shí)要非常小心,避免造成服務(wù)器過度負(fù)擔(dān)。雖然支持 Session 的 Binding 對象缺省就會啟用 PreSession 模式,但依然建議你強(qiáng)制指定 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
【編輯推薦】