Autostart is a really cool feature of Windows Server AppFabric. Recently I was asked about how you can do some kind of process initialization in your code with Autostart (which the documentation implies that you can do). This led to a discussion with a number of questions that we want to address
- What does Autostart really do?
- How much faster is the first call to my service if I use Autostart?
- How can I write code that is called when the service is auto-started?
What does Autostart do?
It depends on your particular service but there is a fair bit of work that has to be done when starting a service. The work includes setting up ASP.NET, spinning up an appdomain, compiling (if required) and some other misc things. If you want the details use Reflector to look at Microsoft.ApplicationServer.Hosting.AutoStart.ApplicationServerAutoStartProvider and System.ServiceModel.Activation.ServiceHostingEnvironment.EnsureServiceAvilable as these classes do the work. One thing it does not do is create an instance of your service class or call any methods on it.
How much faster is the first call to my service if I use Autostart?
A lot faster. Try an order of magnitude faster. In my testing I published a service to two IIS Web applications, one with Autostart and one without. As you can see the call to the Autostart service was significantly faster.
How can I write code that is called when the service is auto-started?
You can try using a custom ServiceHostFactory or add code to Global.asax Application_Startup – unfortunately neither of these are going to give you what you want. They won’t be called until the service is activated.
The only real answer to this is to implement your own Autostart provider and adding it to the IIS applicationHost.config. ScottGu wrote up a good blog post on how to do this here. Unfortunately you can have only one autostart provider so if you add one, you will replace the AppFabric autostart provider.
I know what you are thinking… why don’t I just do my thing and then call the AppFabric autostart provider. Nice try but ApplicationServerAutoStartProvider is internal so unless you resort to reflection tricks you can’t call it.
Read the complete post here