Fire event when client connects to WCF-hosted endpoint

后端 未结 2 775
隐瞒了意图╮
隐瞒了意图╮ 2021-01-02 03:52

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

相关标签:
2条回答
  • 2021-01-02 04:19

    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

    0 讨论(0)
  • 2021-01-02 04:26

    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.

    0 讨论(0)
提交回复
热议问题