I saw a code as below in a tutorial of EF code first
, MVC
and StructureMap
to create a Context Per Request
pattern:
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 ... all need IunitOfWork
in their constructor .
as you can see it just uses HttpContextScoped()
for the Context
not others and in the EndRequest
event it calls ReleaseAndDisposeAllHttpScopedObjects()
.
1- is this a correct approach ?
2- shall I use HttpContextScoped() for all other Service layer Interfaces
or not just for IUnitOfWork
? e.g
x.For<IFirstEntity>().Use<FirstEntity>();
or
x.For<IFirstEntity>().HttpContextScoped().Use(() => new FirstEntity());
3- ReleaseAndDisposeAllHttpScopedObjects()
disposes all instances or just disposes Context
?