Thursday, 6 October 2011

StructureMap MVC3 Inject Repository Into a Controller

Been working on this for a while and had to pull together information from various sources.

The way i finally got it to work (and this will need to be refactored further) was to ensure that the Type you put into the Use() method is named - otherwise you'll get the exception: "No Parameterless Constructor...".

I am not using the StructureMap configuration file, but instead the Fluent Interface, Registry DSL to configure StructureMap programmatically in the Application_Start event of Global.asax.cs:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    StructureMap.ObjectFactory.Initialize(x =>
        {
            x.UseDefaultStructureMapConfigFile = false;
            x.For<System.Web.Mvc.IController>().Use<MvcSMTest.Controllers.BlogController>().Named("blog");
            x.For<MvcSMTest.Models.IPostRepository>().Use<MvcSMTest.Models.InMemoryPostRepository>();
        });
    ControllerBuilder.Current.SetControllerFactory(new MvcSMTest.Controllers.MyControllerFactory());
}

No comments:

Post a Comment