WCF:如何找出会话何时结束?

5 session wcf

我有一个使用会话的WCF应用程序.

会话结束时是否有任何中心事件被抛出?如何找出会话何时结束WITHOUT(!)调用方法(网络断开连接,客户端崩溃 - 所以没有"注销"方法调用)?

服务器托管为:

[ServiceBehavior(
    InstanceContextMode = InstanceContextMode.PerSession,
    ConcurrencyMode = ConcurrencyMode.Reentrant,
    UseSynchronizationContext = false,
    IncludeExceptionDetailInFaults = true
)]
Run Code Online (Sandbox Code Playgroud)

基本上是因为它使用的是回调接口.

现在,我基本上需要在会话终止时对从后端存储创建的实例进行解耦;)

有任何想法吗?

Hel*_*Sam 9

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class MyService : IService
{
    public MyService()
    {
        // Session opened here
        OperationContext.Current.InstanceContext.Closed += InstanceContext_Closed;
        // get the callback instance here if needed
        // OperationContext.Current.GetCallbackChannel<IServiceCallback>()
    }

    private void InstanceContext_Closed(object sender, EventArgs e)
    {
        // Session closed here
    }
}
Run Code Online (Sandbox Code Playgroud)

该代码不适用于Single/PerCall InstanceContextMode.


Shi*_*iji 4

这里有一个关于实例上下文的很好的描述

实例上下文源自CommunicationObject

通信对象有一个关闭事件。

我自己没有这样做,但理论上应该可以通过挂钩此事件,在会话关闭时使用此事件与后端存储分离。