Deferring starts with Castle’s StartableFacility

If you’re using Castle Windsor as your IoC container, the StartableFacility is great simple way to start up services like timers, socket listeners, etc that run for the duration of your application and require two-step initialization — i.e., constructing them then starting them. All you have to do is implement an IStartable interface, with a Start() and Stop() method and Castle will do the rest for you.

The StartableFacility will start each service eagerly by default, as soon as all of its dependencies have been registered in the container. But what if your services take a long time to start up, or you want more control over the time at which they start?

One option is to use the facility’s built-in Deferred Mode that waits until all components have been registered before starting any services.

If that is too early however, you can register all your IStartable components, but not drop the StartableFacility into the container until you want to start them. It will immediately start them all.

public void RegisterServices()
{
    // register startable services
    container.Register(Component.For...));
}

public void StartServices()
{
    // drop this in when you're ready to start them
    container.AddFacility<StartableFacility>();
}

If you need even more fine-grain control, don’t register the facility at all — just loop through all your IStartable components and call Start() on them manually.

May 9, 2012

Leave a Reply