tags:

views:

1370

answers:

2

What is the best way to get notified when a WCF service is first started?

Is there something similar to the Application_Start method in the Global.asax for an ASP.NET application?

+4  A: 

Since it's just a class, you can use a static constructor which will be called the first time the Type is used.

public Service : IContract
{
    public Service(){ // regular constructor }
    static Service(){ // Only called first time it's used. }
}
Paul Alexander
I was hoping for something more host-specific, i.e. something in the application that's hosting the service.
+3  A: 

Well, that might be a bit tricky since the preferred way of calling WCF services is on a "per-call" basis, e.g. you don't really have anything that's "started" and then just hangs around, really.

If you're hosting your service in IIS or WAS, it's even "on-demand loading" of your service host - when a message arrives, the host is instanciated and handles the request.

If you self-host, you either have a console or Winforms app - so you could hook into there to know when they start. If you have a Windows service to host your service host, you most likely override the OnStart and OnStop methods on the ServiceBase class --> hook into there.

The question is more: what exactly are you trying to accomplish? Just logging or something like that, or do you want to have something built up in memory to stick around??

Marc

marc_s
(-1) I really don't understand how this "answer" helps anyone. You basically asked him back and didn't answered his question.
Eran Betzalel
I tried to explain that there's nothing exactly like Application_Start in WCF, but tried to provide ideas where he could hook into to detect what he needs to detect.... sorry you feel that way - I tried my best, but feel free to provide a better answer!
marc_s
Paul Alexander supplied a better answer that actually helped me a lot.
Eran Betzalel
This answers the question - there is no start event for the application, they're on demand. Presumbly there must be a way of tying into the AppDomain.AssemblyLoaded but at that point it's too late
Chris S