WCF中低服务对象的释放,可以通过多种方法来进行实现,其中一个,ReleaseServiceInstance这一WCF释放服务对象的方式应该是最直接的方式了。看下面例子的输出结果,我们可以看到在客户端代理对象释放之前,服务实例就被释放了。
WCF释放服务对象具体代码示例:
- [ServiceContract(SessionModeSessionMode = SessionMode.Required)]
- public interface IMyService
- {
- [OperationContract]
- void Test();
- }
- [ServiceBehavior(InstanceContextModeInstanceContextMode =
InstanceContextMode.PerSession)]- public class MyServie : IMyService, IDisposable
- {
- public MyServie()
- {
- Console.WriteLine("Constructor");
- }
- [OperationBehavior]
- public void Test()
- {
- OperationContext.Current.InstanceContext.ReleaseServiceInstance();
- }
- 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();
- Thread.Sleep(2000);
- Console.WriteLine("Dispose Client Proxy...");
- }
- }
- }
输出:
- Constructor
- Dispose
- Dispose Client Proxy...
以上就是对WCF释放服务对象的相关介绍。
【编辑推荐】