tags:

views:

663

answers:

1

I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost?

+4  A: 

You don't need to inherit ServiceHost. There are other approaches to your problem.

You can pass an instance of the service class, instead of a type to ServiceHost. Thus, you can create the instance before you start the ServiceHost, and add your own event handlers to any events it exposes.

Here's some sample code:

MyService svc = new MyService();
svc.SomeEvent += new MyEventDelegate(this.OnSomeEvent);
ServiceHost host = new ServiceHost(svc);
host.Open();

There are some caveats when using this approach, as described in http://msdn.microsoft.com/en-us/library/ms585487.aspx

Or you could have a well-known signleton class, that your service instances know about and explicitly call its methods when events happen.

Franci Penov
Nice! Both approaches make perfect sense to me; I feel foolish I didn't think of either one of those myself. I guess I've just been blinded by the complexity of WCF itself, since its new to me.
dotnetengineer