WCF and AppFabric Auto-Start

Auto-start 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 Auto-start (which the documentation implies that you can do).  This led to a discussion with a number of questions that we want to address

  1. What does Auto-start really do?
  2. How much faster is the first call to my service if I use Auto-start?
  3. How can I write code that is called when the service is auto-started?

endpoint.tv - WCF and AppFabric Auto-Start

Download WCF / AppFabric Auto-Start Sample Code

What does Auto-start 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.auto-start.ApplicationServerauto-startProvider 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 Auto-start?

A lot faster.  Try an order of magnitude faster.  In my testing I published a service to two IIS Web applications, one with Auto-start and one without.  As you can see the call to the Auto-start service was significantly faster.

SNAGHTML638735b

How can I write code that is called when the service is auto-started?

You can create a custom service host factory that does the initialization.

 

 public class TestServiceHostFactory : ServiceHostFactoryBase

{

    public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)

    {

        ProcessEvents.AddEvent("TestServiceHostFactory called");

        TestCache.Load();

        return new ServiceHost(typeof (Testauto-start), baseAddresses);

    }

}

Then in your markup for your .SVC file let WCF know you are using a custom service host factory

 

 <%@ ServiceHost Language="C#" 

Debug="true" 

Service="auto-startWebTest.Testauto-start" 

CodeBehind="Testauto-start.svc.cs" 

Factory="auto-startWebTest.TestServiceHostFactory" %>

Of course this requires that you do this for every service that needs special initialization.  You cannot use Application_Startup from global.asax to do this because it won't be called.

The IIS Warmup Module for IIS 7.5 may be another helpful option that will work without requiring you to implement a custom service host factory.

Update: You cannot use Auto-Start on the root web.  You have to create a web application under the default web site to use auto-start.