Fire event when client connects to WCF-hosted endpoint
Asked Answered
B

2

13

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?

Bothy answered 2/4, 2009 at 21:1 Comment(0)
C
5

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.

Cadwell answered 14/3, 2012 at 14:50 Comment(2)
Thanks! That does answer my question exactlyBothy
For additional infos see: blogs.msdn.com/b/carlosfigueira/archive/2012/02/14/… Especially for WCF 4.0 the proposed way won't work because a Exception is thrown after the Host transistioned to the open stateStairway
A
0

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

Aliber answered 2/4, 2009 at 21:5 Comment(2)
Session-based. Service host fires the Opened event when service host starts up, e.g.: on host.Open() call, not when new client connectsBothy
do you have any advice if it's InstanceContextMode.Single?Sapotaceous

© 2022 - 2024 — McMap. All rights reserved.