I'm not sure if its possible, but I'd like to have a function run as soon as a WCF service is started to generate initial cache data. I'm not worried now about how to implement the cache, my question is strictly about having the function run when the service starts. The service will be RESTful.
The service will eventually be hosted in IIS and is using .Net Framework 4.5
To open WCF Test Client, open Developer Command Prompt for Visual Studio and execute WcfTestClient.exe. Select Add Service from the File menu. Type http://localhost:8080/hello into the address box and click OK. Make sure the service is running or else this step fails.
There are three types of hosting environments for WCF services: IIS, WAS, and self-hosting. The term “self-hosting” refers to any application that provides its own code to initialize the hosting environment. This includes console, Windows Forms, WPF, and managed Windows services.
Open your Visual Studio if you are using Windows Vista or Windows 7, then open Visual Studio in Administrator mode and create a new project of type Windows Service like in the following diagram. Add a reference to your WCF service library from Project Add Reference Browse Select your WCF service .
In order to consume a WCF service, a client application must first obtain or generate a proxy class. We also need a configuration file to specify things such as the binding of the service, the address of the service, and the contract. To generate these two files, we can use the svcutil.exe tool from the command line.
The easiest way is to create an App_Code
folder underneath your WCF project root, create a class (I'll call it Initializer
but it doesn't matter. The important part is the method name) like so:
public class Initializer { public static void AppInitialize() { // This will get called on startup } }
More information about AppInitialize
can be found here.
What @KirkWoll suggested works, but only if you're in IIS and that's the only AppInitialize static method under App_Code. If you want to do initialization on a per-service basis, if you have a different AppInitialize method or if you're not under IIS, you have these other options:
ServiceHost.Open()
, so you can initialize it thereAn example of a custom factory is shown below:
public class MyFactory : ServiceHostFactory { protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses); host.Opening += new EventHandler(host_Opening); return host; } void host_Opening(object sender, EventArgs e) { // do initialization here } }
}
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