WCF释放服务对象最直接方式解读

WCF中低服务对象的释放,可以通过多种方法来进行实现,其中一个,ReleaseServiceInstance这一WCF释放服务对象的方式应该是最直接的方式了。看下面例子的输出结果,我们可以看到在客户端代理对象释放之前,服务实例就被释放了。

WCF释放服务对象具体代码示例:

 
 
 
  1. [ServiceContract(SessionModeSessionMode = SessionMode.Required)]  
  2. public interface IMyService  
  3. {  
  4. [OperationContract]  
  5. void Test();  
  6. }  
  7. [ServiceBehavior(InstanceContextModeInstanceContextMode = 
    InstanceContextMode.PerSession)]  
  8. public class MyServie : IMyService, IDisposable  
  9. {  
  10. public MyServie()  
  11. {  
  12. Console.WriteLine("Constructor");  
  13. }  
  14. [OperationBehavior]  
  15. public void Test()  
  16. {  
  17. OperationContext.Current.InstanceContext.ReleaseServiceInstance();  
  18. }  
  19. public void Dispose()  
  20. {  
  21. Console.WriteLine("Dispose");  
  22. }  
  23. }  
  24. public class WcfTest  
  25. {  
  26. public static void Test()  
  27. {  
  28. AppDomain.CreateDomain("Server").DoCallBack(delegate  
  29. {  
  30. ServiceHost host = new ServiceHost(typeof(MyServie), 
    new Uri("http://localhost:8080/MyService"));  
  31. host.AddServiceEndpoint(typeof(IMyService), new WSHttpBinding(), "");  
  32. host.Open();  
  33. });  
  34. //-----------------------  
  35. IMyService channel = ChannelFactory<IMyService>.CreateChannel
    (new WSHttpBinding(),   
  36. new EndpointAddress("http://localhost:8080/MyService"));  
  37. using (channel as IDisposable)  
  38. {  
  39. channel.Test();  
  40. Thread.Sleep(2000);  
  41. Console.WriteLine("Dispose Client Proxy...");  
  42. }  
  43. }  

输出:

 
 
 
  1. Constructor  
  2. Dispose  
  3. Dispose Client Proxy... 

以上就是对WCF释放服务对象的相关介绍。

【编辑推荐】

  1. WCF单例服务中可扩展性认识
  2. WCF单例模式各种类型分析对比
  3. WCF服务实例单一性实现案例解读
  4. WCF服务寄宿相关使用概念详解
  5. WCF用户验证基本实现原理
THE END