在 PerSession 中,如何让服务上的 Dispose() 触发?在下面的代码中 Dispose() 没有被调用。当我调用 .Close() 或让会话超时时都不会。
如果我将服务更改为 PerCall,则调用 Dispose()(每个方法调用)。使用 PerSession 我得到一个会话(用 serviceStartTime 测试)。
服务
[ServiceBehavior (InstanceContextMode=InstanceContextMode.PerSession)]
public class MagicEightBallService : IEightBall, IDisposable
{
private DateTime serviceStartTime;
public void Dispose()
{
Console.WriteLine("Eightball dispose ... " + OperationContext.Current.SessionId.ToString());
}
public MagicEightBallService()
{
serviceStartTime = DateTime.Now;
Console.WriteLine("Eightball awaits your question " + OperationContext.Current.SessionId.ToString() + " " + serviceStartTime.ToLongTimeString());
}
public string ObtainAnswerToQuestion(string userQuestion)
{
return "maybe " + OperationContext.Current.SessionId.ToString() + " " + serviceStartTime.ToLongTimeString();
}
客户
using (EightBallClient ball = new EightBallClient())
{
while (true)
{
Console.Write("Your question: ");
string question = Console.ReadLine();
if (string.IsNullOrEmpty(question)) break;
try
{
string answer = ball.ObtainAnswerToQuestion(question);
Console.WriteLine("8-ball says: {0}", answer);
}
catch (Exception Ex)
{
Console.WriteLine("ball.ObtainAnswerToQuestion exception " + Ex.Message);
}
}
ball.Close();
}
服务合约
[ServiceContract (SessionMode = SessionMode.Required)]
public interface IEightBall
{
[OperationContract]
string ObtainAnswerToQuestion(string userQuestion);
[OperationContract]
sDoc GetSdoc(int sID);
DateTime CurDateTime();
}
主持人
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ISampleService"
closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:10:00">
<security mode="Message" />
<reliableSession ordered="true"
inactivityTimeout="00:10:00"
enabled="true" />
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="MajicEightBallServiceLib.MagicEightBallService"
behaviorConfiguration="EightBallServiceMEXBehavior" >
<endpoint address=""
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ISampleService"
contract="MajicEightBallServiceLib.IEightBall">
</endpoint>
<endpoint address="mex"
binding ="mexHttpBinding"
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/MagicEightBallService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="EightBallServiceMEXBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
namespace MagicEightBallServiceHost
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("**** Console Based WCF Host *****");
using (ServiceHost serviceHost = new ServiceHost(typeof(MagicEightBallService)))
{
serviceHost.Open();
Console.WriteLine("The service is running");
Console.ReadLine();
}
}
}
}