Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which PreApplicationStartMethod should I use?

I noticed that when I installed StructureMap from NuGet into my ASP.NET MVC3 project, Dave Ebbo's WebActivator package was also added as a dependency.

WebActivator provides a PreApplicationStartMethod attribute and, in the boilerplate code added at install time, it is used to initialise the IoC container and dependency resolver in it's own class, instead of doing this inside Global.asax's Application_Start method.

Given that ASP.NET 4 already has its own System.Web.PreApplicationStartMethodAttribute why was it necessary for WebActivator to supply its own version and for StructureMap to use that?

I am guessing I don't have to use WebActivator's variant?

Added code for Darin:

using System.Web;
using System.Web.Mvc;
using StructureMap;

[assembly: WebActivator.PreApplicationStartMethod(
                    typeof(MyMvcApp.App_Start.StructuremapMvc), "Start")]
// or

[assembly: PreApplicationStartMethod(
                    typeof(MyMvcApp.App_Start.StructuremapMvc), "Start")]

namespace MyMvcApp.App_Start {
  public static class StructuremapMvc {
    public static void Start() {
      var container = (IContainer) IoC.Initialize();
      DependencyResolver.SetResolver(new SmDependencyResolver(container));
    }
  }
}
like image 419
Kev Avatar asked Jan 24 '12 12:01

Kev


1 Answers

NuGet packages for DI containers in ASP.NET MVC 3 usually prefer to use WebActivator to avoid messing with any existing code that you might have in Application_Start. Ninject uses exactly the same approach.

You can have multiple WebActivator.PreApplicationStartMethod attributes in your application and prior to .NET 4.5 a single System.Web.PreApplicationStartMethodAttribute.

like image 140
Darin Dimitrov Avatar answered Sep 19 '22 22:09

Darin Dimitrov