Thanks to a comment by thangchung in my last post about the global.asax, I’m going to write up a post using a bootstrapper in my global.cs. So what does that mean? Well basically it’s a technique to boot up your mvc app. Let’s get started!
Step 1: Create your task interface. Mine looks like this:
public interface IStartUpTask
{
void Configure();
}
Pretty simple right? Let’s keep on…
Step 2: Configure StructureMap, otherwise you’re going to have a mess. In my Scan() from my DependencyRegistry, I added x.AddAllTypesOf<IStartUpTask>(); and the completed Scan looks like this:
Scan(x =>
{
x.TheCallingAssembly();
x.AddAllTypesOf<IStartUpTask>();
x.WithDefaultConventions();
});
Step 3: Create the Bootstrapper class. Mine looks like this:
public class Bootstrapper
{
static Bootstrapper()
{
DependencyResolution.DependencyRegistrar.EnsureDependenciesRegistered();
}
public static void StartUp()
{
var startUpTasks = ObjectFactory.GetAllInstances<IStartUpTask>();
foreach (var task in startUpTasks)
task.Configure();
}
}
The DependencyRegistrar mentioned above, I basically stole from the sample code in the ASP.NET MVC in Action book. I made a few modifications, but not much.
Step 4: Configure your configuration files for all the junk you need to start up.
- Routes - I took my RouteConfigurator and made it implement IStartUpTask and renamed RegisterRoutes to Configure.
- MvcContrib InputBuilder – Just made a new class that looks like this:
public class MvcContribConfigurer : IStartUpTask
{
public void Configure()
{
MvcContrib.UI.InputBuilder.InputBuilder.BootStrap();
}
}
- Automapper - I already had a configure, so I just tacked on the : IStartUpTask like this:
public class AutoMapperConfigurator : IStartUpTask
{
public void Configure()
{
Mapper.Initialize(x => x.AddProfile<MyProfile>());
}
}
- ControllerFactory – I created a new class for it and it looks like this:
public class ControllerConfigurer : IStartUpTask
{
public void Configure()
{
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());
}
}
That’s it! So essentially the Global.cs went from this:
protected void Application_Start()
{
MvcContrib.UI.InputBuilder.InputBuilder.BootStrap();
DependencyRegistrar.EnsureDependenciesRegistered();
new RouteConfigurator().RegisterRoutes();
AutoMapperConfigurator.Configure();
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());
}
to this:
protected void Application_Start()
{
Bootstrapper.StartUp();
}
Pretty cool stuff! Thanks thangchung for bringing it up!
As always, please comment and thanks for reading!