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?)
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:
you could create your own custom ServiceHost
class that will do something when it gets instantiated
you can add some "initialization" code to each of your service class methods to handle your needs
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With