Running a function on WCF start up
Solution 1
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:
- If using .NET Framework 4.5, and under IIS: You can use the service configuration method which will be called when the service is running. More info at http://msdn.microsoft.com/en-us/library/hh205277(v=vs.110).aspx.
- If you're self-hosting your service, you control when the service starts (the call to
ServiceHost.Open()
, so you can initialize it there - If you're under IIS, and not on 4.5, you can use a service host factory and a custom service host to be called when the service host is being opened. At that point you can do your initialization. You can find more about service host factories at http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/14/wcf-extensibility-servicehostfactory.aspx.
An 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
}
}
}
Solution 2
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.
Solution 3
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
}
Comments
-
SmashCode over 4 years
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
-
SmashCode almost 12 yearsThat might be exactly what I'm looking for. Does it matter if the service is hosted in IIS?
-
Kirk Woll almost 12 yearsYes, in fact it requires IIS.
-
Kirk Woll almost 12 yearsFor what it's worth, none of those options worked for me -- I had to use
AppInitialize
because I was taking over handling of.svc
files to be auto-generated. But that aside, nice thorough answer. -
tntwyckoff over 8 yearsAnd I experienced one strange side-effect using the IIS/4.5 'service configuration method': inside of "Configure" i had to add the line below, because it no longer read my web.config file settings and everything went haywire:
config.LoadFromConfiguration ()
-
Quarkly about 8 yearsI found this to be a poor option. The module containing the 'AppInitialize' is not compiled with the project, but provided as 'content' and compiled dynamically when the service is loaded. As a result, many of the libraries required to properly implement IOC are not available (e.g. System.Reflection). While I agree with the need for a single initialization method, this solution is VERY limited by the fact that it's dynamically compiled.
-
Kirk Woll about 8 years@DRAirey1, you can call any class in your assembly from
AppInitialize
, so I don't understand what you're getting at. -
Quarkly about 8 yearsI'm getting at the fact that the AppInitialized is compiled on-the-fly. If IIS doesn't have the external library around, you get an 'Unable to load module' exception. I tried to feed several assemblies into a MEF container construction and IIS wasn't able to find 'System.Reflection'. I'm sure I could spend several hours constructing an application pool that had every assembly I needed ahead of time, but there's just too much room to screw up with this solution. The 'ServiceHostFactory' answer insures that all the assemblies you need are compiled into the code.
-
bmode almost 8 years@user240374 Very helpful info! Reading the MSDN page that was linked in the main answer, it appears that point of the IIS/4.5 'service configuration method' is to allow you to configure the service in code, rather than from the web.config file. So I guess it makes sense that if you have one of these Configure methods, IIS will ignore the web.config unless you explicitly tell it to go read it.
-
xr280xr almost 6 yearsI find this to be a huge drawback:
When defined, any service configuration settings specified in an app.config or web.config file will be ignored.
I want to execute some code at startup, but not disable file based configuration. -
Piero Alberto about 4 yearsFor me, it works when running code in Visual Studio but not within IIS....
-
Dan Chase over 3 yearsI know this is old, but wanted to comment in case anyone had an answer, this works, until you want to use it to set a variable, to be accessed later from a service (like a configuration of some kind), there's no way I can find to access it, it's all in a different context.
-
Dan Chase over 3 yearsIn case anyone wants a link for this, docs.microsoft.com/en-us/archive/msdn-magazine/2007/september/… states that "The WCF ServiceHost type features two events called Opening and Closing. They are the only proper ways to execute code at service startup and shutdown."