7

What is the best way to create a bootstrapper for my MVC 2 app? I'm using Unity and AutoMapper and want to abstract the loading and configuration of them as much as possible.

A decent example is here (http://weblogs.asp.net/rashid/archive/2009/02/17/use-bootstrapper-in-your-asp-net-mvc-application-and-reduce-code-smell.aspx ), but UnityContainer implements IDisposable and in that example it is never cleaned up. This (Configuring Automapper in Bootstrapper violates Open-Closed Principle?) is also a decent example, but he doesn't deal with the Unity/Disposable problem either.

Here's (http://www.dominicpettifer.co.uk/Blog/42/put-an-ioc-powered-bootstrapper-in-your-asp-net-mvc-application) another great example of how to do a Bootstrapper, but again doesn't address the Unity/Disposable issue.

I thought about keeping my Bootstrapper object around in a static variable and make it implement IDisposable, but that doesn't sound right.

Community
  • 1
  • 1
Jon Gallant
  • 181
  • 1
  • 6

1 Answers1

4

If you keep a reference to the container in the Bootstrapper class you can dispose it on application end.

public static class Bootstrapper
{
    private static IUnityContainer _container;

    public static void Run()
    {
        _container = new UnityContainer();

        // Configure container here...
    }

    public static void Dispose()
    {
        _container.Dispose();
    }
}

public class YourHttpApplication : HttpApplication
{
    protected void Application_Start()
    {
        Bootstrapper.Run();
    }

    protected void Application_End()
    {
        Bootstrapper.Dispose();
    }
}

Or you could return the container from your bootstrapper, keep a reference to it and dispose it on application end.

public class YourHttpApplication : HttpApplication
{
    private IUnityContainer _container;

    protected void Application_Start()
    {
        _container = Bootstrapper.Run();
    }

    protected void Application_End()
    {
        _container.Dispose();
    }
}

Depends on your preference I guess. Apart from that, any of the bootstrapping examples listed in the question should be a good pick for bootstrapping your application.

mrydengren
  • 4,270
  • 2
  • 32
  • 33
  • Why you didn't use a Bootstrapper package and methods from guide? It's may look like this: `Bootstrapper.With.Unity().And.AutoMapper().And.StartupTasks().Start();` – Joseph Katzman Feb 05 '17 at 20:07