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

慕姐8265434
TA貢獻1813條經(jīng)驗 獲得超2個贊
我會使用BeginRequest / EndRequest方法,這有助于確保在請求結(jié)束時正確處理您的上下文。
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貢獻1806條經(jīng)驗 獲得超8個贊
一種方法是訂閱Application_BeginRequest
事件,將DbContext注入當(dāng)前的HttpContext以及Application_EndRequest
從HttpContext和dispose中獲取。介于兩者之間的任何東西(幾乎所有東西:-))都可以從當(dāng)前的HttpContext中獲取DbContext并使用它。而且,是的,你應(yīng)該處理它。順便說一下,你有沒有理由不使用已經(jīng)為你做過的DI框架以及其他有用的東西?
- 3 回答
- 0 關(guān)注
- 767 瀏覽
添加回答
舉報
0/150
提交
取消