我在 的教程中看到了如下代码EF code first,MVC并StructureMap创建了一个Context Per Request模式:
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, SecondEntityand ... 都需要IunitOfWork在他们的构造函数中。
如您所见,它仅HttpContextScoped()用于Context其他人,并且在EndRequest它调用的情况下ReleaseAndDisposeAllHttpScopedObjects()。
1-这是正确的方法吗?
2-我应该将 HttpContextScoped() 用于所有其他Service layer Interfaces还是不只是用于IUnitOfWork?例如
x.For<IFirstEntity>().Use<FirstEntity>();
或者
x.For<IFirstEntity>().HttpContextScoped().Use(() => new FirstEntity());
3-ReleaseAndDisposeAllHttpScopedObjects()处置所有实例还是仅仅处置Context?