Fire event when client connects to WCF-hosted endpoint

社会主义新天地 提交于 2019-12-18 14:54:24

问题


What do I do in order to fire an event when a new client connects to WCF-hosted service?

EDIT: What I'm looking is to get an event when a new session is created or new Channel gets created for a client. Such as: for session closure I'm using:

OperationContext.Current.Channel.Closed += new EventHandler( Channel_Closed );

so what should I be using for session iitiation?


回答1:


I think what you're trying to accomplish is best done by adding a new channel initializer to the service listener(s) after they are created.

Basically, you create a class which implements that interface, then you add it to the service host. If you're self-hosting this is pretty simple:

public class MyHook : IChannelInitializer
{
  public void Initialize(IClientChannel channel)
  {
    // Do whatever.
  }
}

var host = new ServiceHost(typeof(MyService), MYBASEADDRESS);
host.AddServiceEndpoint(typeof(IMyService), new WSHttpBinding(), MYSERVICEADDRESS);
host.Open();

// There will be one per endpoint; you can enumerate them if needed etc.
var dispatcher = host.ChannelDispatchers[0] as ChannelDispatcher;
dispatcher.ChannelInitializers.Add(new MyHook());

Since you are using the per-session instance mode, you will get a new channel created for each new session, the first time a client connects. The channel dispatcher is the object that's responsible for taking the newly created channel and associating it with a particular service object instance (does address matching, etc.). It will run each of the custom initializers on the new channel before your service gets hooked up to it.




回答2:


Depends on your set up - do you do "per call" conversations? Then you don't really get any "client now connected" message per se....

Do you do session-based conversations? Your "ServiceHost" class has two events "Opening" and "Opened", which you can hook into, especially if you self-host your service.

What exactly is it you want to achieve by trapping this event?

Marc



来源:https://stackoverflow.com/questions/711611/fire-event-when-client-connects-to-wcf-hosted-endpoint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!