WCF PreCal模式基本代碼示例解析
作者:佚名
WCF PreCal模式的應用,會每次都調用創建一個服務實例,在實際應用中作用非常大。下面我們就來一起看看它的相關應用技巧。
在WCF實例上下文模式中,PreCal模式是一個比較重要的模式。我們在這篇文章中將會針對WCF PreCal模式的相關概念及應用技巧做一個詳細的闡述,希望朋友們能從中獲得一些幫助。
在WCF PreCal模式下,即便使用同一個代理對象,也會為每次調用創建一個服務實例。調用結束后,服務實例被立即釋放(非垃圾回收)。對于不支持 Session 的 Binding,如 BasicHttpBinding,其缺省行為就是 PreCall。
- [ServiceContract]
- public interface IMyService
- {
- [OperationContract]
- void Test();
- }
- [ServiceBehavior(InstanceContextModeInstanceContextMode =
InstanceContextMode.PerCall)]- 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:df549447-52ba-4c54-9432-31a7a533d9b4
- Dispose
- Constructor:41153804
- Test:urn:uuid:df549447-52ba-4c54-9432-31a7a533d9b4
- Dispose
以上就是我們為大家介紹的WCF PreCal模式的相關介紹。
【編輯推薦】
責任編輯:曹凱
來源:
博客園