ASP.NET MVC中每個(gè)請(qǐng)求一個(gè)DbContext(沒(méi)有IOC容器)如果這已經(jīng)得到回答,請(qǐng)道歉,但如果您不使用IOC容器,如何保證每個(gè)請(qǐng)求有一個(gè)Entity Framework DbContext?(到目前為止,我遇到的答案涉及IOC容器解決方案。)似乎大多數(shù)解決方案都掛鉤到HttpContext.Current.Items字典中,但是如何在請(qǐng)求完成時(shí)保證處理DbContext?(或者EF的處理不是絕對(duì)必要的DbContext嗎?)編輯我目前正在我的控制器中實(shí)例化和處理我的DbContext,但我在ActionFilters和我的MembershipProvider中也有幾個(gè)單獨(dú)的DbContext實(shí)例(我剛注意到,也有幾個(gè)驗(yàn)證器)。因此,我認(rèn)為集中我的DbContext的實(shí)例化和存儲(chǔ)以減少開(kāi)銷可能是個(gè)好主意。
3 回答

慕姐8265434
TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
我會(huì)使用BeginRequest / EndRequest方法,這有助于確保在請(qǐng)求結(jié)束時(shí)正確處理您的上下文。
protected virtual void Application_BeginRequest(){ HttpContext.Current.Items["_EntityContext"] = new EntityContext();}protected virtual void Application_EndRequest(){ var entityContext = HttpContext.Current.Items["_EntityContext"] as EntityContext; if (entityContext != null) entityContext.Dispose();}
在你的EntityContext類中......
public class EntityContext{ public static EntityContext Current { get { return HttpContext.Current.Items["_EntityContext"] as EntityContext; } }}

慕森卡
TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
一種方法是訂閱Application_BeginRequest
事件,將DbContext注入當(dāng)前的HttpContext以及Application_EndRequest
從HttpContext和dispose中獲取。介于兩者之間的任何東西(幾乎所有東西:-))都可以從當(dāng)前的HttpContext中獲取DbContext并使用它。而且,是的,你應(yīng)該處理它。順便說(shuō)一下,你有沒(méi)有理由不使用已經(jīng)為你做過(guò)的DI框架以及其他有用的東西?
- 3 回答
- 0 關(guān)注
- 763 瀏覽
添加回答
舉報(bào)
0/150
提交
取消