Thursday, December 13, 2012

Application Startup Tasks in FubuMVC

Within my applications I often have a need to perform some kind of initialization whenever the application starts up. I typically call these application startup tasks. Because I use Structuremap as my dependency injection tool it is really easy to register and scan for specific implementations of an interface. So I usually create the following:

public interface IApplicationStartupTask
    void Execute();

Now when I want all of the implementation of this interface I can just inject an enumeration into some type using constructor injection.

IEnumerable<IApplicationStartupTask> tasks

But here's the problem. The only way I know how to instantiate an object on application startup without new-ing it up explicitly is by doing this:


Really what I end up doing is this though:

ObjectFactory.GetAllInstances<IApplicationStartupTask>().Each(x => x.Execute);

Throughout my application I try very hard not to use ObjectFactory explicitly but I've never found a way around it when trying to execute these startup tasks. Because this hard dependency has "just worked" for me I've just moved on and not worried about it. But today I changed the way I register Structuremap within FubuMVC and my hard dependency no longer worked. I usually configure FubuMVC like this:


But I changed it to this

Now a new Container is used per unit of work instead of the global Container. I went out searching for the "right way" of doing this and with some help from Jeremy Miller I discovered that what I was trying to do is already built into FubuMVC!

Jeremy says..." Use the IActivator interface from Bottles and register that with your container. Or really, just convert your IApplicationStartupTask's to IActivator's and you're good to go."

No comments:

Post a Comment