Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something when my WCF service started

Tags:

c#

wcf

startup

I want to do something just after my WCF service started. How can do it?

In fact,I should update some variable of my service every 10 minutes. So I put my update code in a thread. But I dont know how start this thread when service started (Is there anything liked Form_Load event in WCF services?)

like image 256
SuB Avatar asked Aug 30 '11 20:08

SuB


2 Answers

There is typically no parts of your WCF service that is "just hanging around" in memory ready to do something.... WCF is NOT ASP.NET !

The default setup when hosting in IIS is this:

  • IIS listens on a specific port/URL for a request - there's not a single trace of your WCF service anywhere in memory

  • when a first request comes in, IIS will spin up a ServiceHost - a class that can "host" a service

  • this service host will then look at the request has come in and depending on the target URL, it will decide which service class to instantiate to handle this request. The service class (your service implementation) is then created and the appropriate method on that service class is called and executed, and once that's completed, the service class is disposed

So basically, there are two points where you can hook into:

  1. you could create your own custom ServiceHost class that will do something when it gets instantiated

  2. you can add some "initialization" code to each of your service class methods to handle your needs

like image 65
marc_s Avatar answered Oct 11 '22 16:10

marc_s


It's difficult to keep a thread running on a server. As soon as the last session terminates the application shuts down. Some hosting providers also recycle the app pool on a schedule which kills any chance of keeping a thread running.

That aside, WCF Services don't actually run. They act like web pages triggered by a request. The sensible place to add init code would be in your Application_Start in Global.asax. This would get called once when the application starts (the first request is made).

If you would rather do something on each request to your services, you could hook the Application_BeginRequest event also in Global.asax.

like image 38
TheCodeKing Avatar answered Oct 11 '22 17:10

TheCodeKing