How to register per request dependencies using StructureMap, MVC 5, and WebApi 2? entity-framework-6 structuremap


I have a Mvc5-WebApi2 application that uses StructureMap for dependency injection using the StructureMap.Mvc5 and StructureMap.WebApi2 Nuget packages. I want to register my EF 6 DbContext with HttpContext lifecycle for both MVC and Web controllers. Can someone point me to a succinct explanation on how to achieve this for both MVC and WebApi? In general, how can I register certain dependencies in a per request container and others in the parent container?

5/27/2015 2:09:30 PM

Accepted Answer

The recommended approach to HttpContext bound life-cycles is to harness StructureMap's nested containers.

This works by configuring a StructureMap container and then creating a nested instance of the container and storing it in the HttpContext at the start of the request and using that container throughout the HttpRequest before disposing of it at the end (see here for the source code).

You can set this up yourself (see this blog post on how to do this) or you can use both of these NuGet packages to do it for you:

StructureMap.MVC5 and StructureMap.WebApi.

Once set up you can then register your DbContext in the normal fashion:

this.For<DbContext>.Use(new DbContext(connectionString));

I hope this helps. If you do have any questions then I'll try my best to help.

6/1/2015 8:54:10 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow