Starting a Hosted Service
How do I run some code during service start time if I'm using an IIS hosted service?
In a normal executable or NT service, your code is responsible for creating the ServiceHost that contains the web services. In IIS, it is the platform activation code that serves this role, leaving no code necessary for you to deal with the host. Not having any code is convenient most of the time but suddenly becomes inconvenient when you need to run some bit of code before your service can successfully start.
There are a few options that you have to solve this problem. You could put the code inside one of the paths that gets executed while your service is being created, such as a constructor or behavior. This approach has some timing issues because you may need to order the occurrence of events during service creation in a particular way. You could alternatively put the code inside one of the paths that gets executed by the host, such as a globally or site scoped ASP.NET file. This is also a very clumsy solution because it requires learning about another technology and you have to deal with the application event model of the host.
A better solution to this problem is to create a custom ServiceHostFactory. The factory, which is a configurable option through the SVC file, is the extensibility point responsible for stamping out instances of ServiceHost. Your factory can then create a custom ServiceHost that has overridden whatever methods you need to hook the startup process. The same code can even be used when you're not hosted in IIS, making this a portable solution as well if you need to change your hosting environment. We have a sample showing how to use ServiceHostFactory in exactly this way.
Next time: Just a Bit of Caching
Comments
Anonymous
April 12, 2007
I've done a bit of grouping for the remaining binding elements as there are fourteen non-transport bindingAnonymous
September 25, 2007
I've configured my web site in IIS with multiple bindings but my web service can no longer run because