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 imp
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.
In my case I did like below. I have Windows service project that hosted a WCF Rest service. I wrote below code in my windows service project MyService.cs
protected override void OnStart(string[] args)
{
try
{
ServiceHost myServiceHost = new ServiceHost(typeof(myservice));
myServiceHost.Opening += OnServiceHostOpening;
myServiceHost.Open();
}
catch (Exception ex)
{
//handle exception
}
}
private void OnServiceHostOpening(object sender, EventArgs e)
{
//do something
}
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
}
}
}