Is StructureMap HttpContextScoped required?

In the EF code first , MVC and StructureMap tutorial, I saw the code as shown below to create the Context Per Request template:

  protected void Application_Start() { ... initStructureMap(); } private static void initStructureMap() { ObjectFactory.Initialize(x => { x.For<IUnitOfWork>().HttpContextScoped().Use(() => new Context()); x.For<IFirstEntity>().Use<FirstEntity>(); x.For<ISecondEntity>().Use<SecondEntity>(); x.For<IThirdEntity>().Use<ThirdEntity>(); }); ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory()); } protected void Application_EndRequest(object sender, EventArgs e) { ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects(); } public class StructureMapControllerFactory : DefaultControllerFactory { protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return ObjectFactory.GetInstance(controllerType) as Controller; } } 

FirstEntity , SecondEntity and ... IunitOfWork needs IunitOfWork in its constructor.

as you can see, it just uses HttpContextScoped() for Context not others, and in the EndRequest event it calls ReleaseAndDisposeAllHttpScopedObjects() .

1- is this the right approach?

2- use HttpContextScoped () for all other Service layer Interfaces or not only for IunitOfWork ? eg

 x.For<IFirstEntity>().Use<FirstEntity>(); 

or

 x.For<IFirstEntity>().HttpContextScoped().Use(() => new FirstEntity()); 

3- ReleaseAndDisposeAllHttpScopedObjects() uses all instances or just has Context ?

+8
asp.net-mvc-3 entity-framework structuremap
source share
1 answer

The convention for web applications is that you keep the same ORM / UnitOfWork context during the entire HTTP request. This is done in order to work with the same objects during the query, maintain data consistency and minimize database calls made. The HttpContextScoped life cycle ensures that the same UoW instance is used during a request for all instances that depend on it.

So 1) yes, that's right

As for the rest of the "service level interfaces", it depends on whether it should be the same instance during the entire request. Ask yourself: "will the state of this object be during the entire request"? For most "services" this is not so. Also note that creating something "HttpContextScoped" will also cause all its dependencies to remain during this area.

It makes me say 2) In most cases, no

ReleaseAndDisposeAllHttpScopedObjects places all the objects in the container registered with HttpContextScoped . By default, objects are distributed as transients (a new instance for each call) in the Structuremap.

So 3) IUnitOfWork instance will be deleted.

+8
source

All Articles