2013-03-28 110 views
1

我得到了一個使用EF來處理數據庫的ASP.NET MVC應用程序。我使用DDD作爲體系結構,並且獲得了Repository和Service模式。StructureMap,ASP.NET和實體框架DbContext配置

我正在嘗試使用StructureMap for DI,但由於某種原因,我的數據庫在第一次請求後才被處理。

編輯:我的錯誤,我得到的錯誤是

操作無法完成,因爲的DbContext已經佈置 。

看來,我得到它在倉庫中,例如在:

public class AccountRepository : Repository<Account>, IAccountRepository 
{ 
    public AccountRepository(MyDbContext context) : base(context) { } 

    public Account FindAccountByEmailAddress(string emailAddress, bool loadRelatedRoles = false) 
    { 
     IQueryable<Account> query = (from a in Entity 
            where a.LoweredEmailAddress == emailAddress.ToLower() 
            select a); 
     if (loadRelatedRoles) 
     { 
      return query.Include(a => a.Roles).FirstOrDefault(); 
     } 

     return query.FirstOrDefault(); 
    } 
} 

在的Application_BeginRequest我使用

 ObjectFactory.Configure(x => 
     { 
      x.For(typeof(MyDbContext)) 
       .HttpContextScoped(); 
     }); 

註冊DB爲了儲備它作爲每個請求的一個實例。

在Application_EndRequest我放開了使用請求:

protected void Application_EndRequest(object sender, EventArgs e) 
    { 
     StructureMap.ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects(); 
    } 

我缺少的東西?或者我的接近是可以的,我的Repository實現可能會遇到問題。

+1

這是否每次都發生,或者只有在'loadRelatedRoles'爲真時纔會發生?我試圖在這裏檢查是否「懶惰」添加了「角色」,並且稍後嘗試獲取它們(在處理上下文之後)。你是否也可以顯示存儲庫(注入和)使用的Controller代碼? – Tallmaris

+0

我可能是錯的,但並不是所有的請求都會拋出一個開始和結束請求?即每個CSS文件或圖像,它可能是你不必要地處理對象? – Slicksim

+0

關於你的第一個問題 - 我使用懶惰,但我已經刪除了測試,錯誤繼續出現。通過下面的評論進一步診斷後 - 我注意到我得到了這個問題,因爲我在Application_Start和Application_OnPostAuthenticateRequest中連接到數據庫,它似乎使用不同的HttpContext。 – OzB

回答

1

好吧,我發現這個問題 - 這似乎是我的Application_Start代碼在調用一個以上的時間,我在某些情況下使用懶惰 - 導致的空引用到數據庫的上下文保存。

感謝您的幫助!