Wednesday, August 27, 2014

StructureMap.MVC5

...is a NuGet package which allows one to bring in dependencies at an ASP.NET MVC controller implicitly when the constructor is called like so:

namespace Whatever
{
   public class MyController : Controller
   {
      public IMyRepository MyRepository { get; set; }
      
      public IFrameController(IMyRepository myRepository)
      {
         MyRepository = myRepository;
      }
      
      public ActionResult Index()
      {
         var model = MyRepository.GetThatOneThingWeNeed();
         return View(model);
      }
   }
}

 
 

In this example, when one tries to visit http://www.example.com/my/ at a browser, the appropriate class which implements the IMyRepository interface is magically hydrated at the controller's constructor. The NuGet package creates a "DependencyResolution" folder at an MVC project to facilitate the code to empower this trick. The code in the classes at the App_Start folder are dressed up some to appropriately utilize what is in the DependencyResolution folder too. DefaultRegistry.cs in DependencyResolution seems to be the new place to wire up the dependencies one used to wire up in the Global.asax.cs in yesteryear (MVC3). StructureMap.WebApi2 is the sister NuGet package for the Web API. WebActivatorEx is used to pull some of the new code that comes with the other two packages out into attributes in lieu of having it liter Global.asax.cs.

No comments:

Post a Comment