Reputation: 1469
I have a WCF service that is hosted by a windows service. I can't figure out how to inform the windows service when a client connects to the WCF service. Basically all I have in the windows service to start the WCF service is this:
private ServiceHost sHost;
WCF.WCFService wcfService = new WCF.WCFService();
sHost = new ServiceHost(wcfService);
sHost.Open();
I am able to call methods in the WCF service with the windows service using the wcfService object. Is there some way to have some kind of event that would fire when a client connects to WCF service?
Upvotes: 2
Views: 6141
Reputation: 1469
I found the best answer here: Subscribe to events within a WCF service
As suspected you can create an event handler in the WCF service that can be picked up by the host.
Upvotes: 1
Reputation: 28728
The service runs as an object which is instantiated according to the ServiceBehaviourAttribute
property InstanceContextMode
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService : IMyService
{
// ...
The values for InstanceContextMode are
Single
- a single instance of the service runs for all sessions and callsPerSession
- an instance of the service runs for each session (i.e. each client)PerCall
- an instance of the service is instantiated for each call, even from a single clientThe default value is PerSession
, and this makes sense for most scenarios. Assuming you're using PerSession
, you can put whatever 'connect logic' you like inside the constructor for the service.
// you don't need to specify PerSession as it is default, but I have for clarity
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService : IMyService
{
public MyService()
{
// constructor will be called for each new client session
// eg fire an Event, log a new client has connected, etc
}
// ...
}
You need to be careful running code in the constructor, because the service will not be available until the constructor has completed. If you want to do anything that may take time, fire an event or send a thread to perform that work.
Upvotes: 1