Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire event when client connects to WCF-hosted endpoint

Tags:

.net-3.5

wcf

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?

like image 450
galets Avatar asked Apr 02 '09 21:04

galets


1 Answers

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.

like image 111
Michael Edenfield Avatar answered Sep 27 '22 03:09

Michael Edenfield