我看到如下代碼中的EF code first
,MVC
和StructureMap
教程創建Context Per Request
模式:是StructureMap HttpContextScoped必要的嗎?
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
和......都需要IunitOfWork
在其構造。
正如你所看到的,只是使用HttpContextScoped()
代替Context
而不是其他代碼,在EndRequest
事件中它調用ReleaseAndDisposeAllHttpScopedObjects()
。
1-這是一個正確的方法?
2-我應該使用HttpContextScoped()爲所有其他Service layer Interfaces
或不只是爲IUnitOfWork
? e.g
x.For<IFirstEntity>().Use<FirstEntity>();
或
x.For<IFirstEntity>().HttpContextScoped().Use(() => new FirstEntity());
3- ReleaseAndDisposeAllHttpScopedObjects()
處置所有實例或只是處置Context
?
我更新了問題2 –
已更新的回答。除非需要保持相同的狀態,否則創建實例的成本很高,並且可以在請求期間共享狀態,請使用瞬態對象。 – PHeiberg
謝謝,我的問題是當這些實例將被處置?他們是否也在EndRequest中處理? –