2013-01-04 46 views
2

我正試圖與Ninject握手,似乎無法找到任何有助於解決問題的文章。我創建了一個簡單的包含Web,業務邏輯和數據訪問層的n層解決方案。在DAL中,我爲我的數據庫(簡單的兩個表格數據庫)和通用存儲庫(IRepositoryItemRepository)創建了一個模型,如下所示。在多層應用程序的DbContext上使用Ninject

public interface IRepository<T> where T : class 
{ 
    IQueryable<T> GetAll(); 
} 

此接口的實現如下所示。

public class ItemRepository : IRepository<Item> 
{ 

    public IQueryable<Item> GetAll() 
    { 
     IQueryable<Item> result; 
     using (GenericsEntities DB = new GenericsEntities()) { 
      result = DB.Set<Item>(); 
     } 
     return result; 
    } 

} 

在我BLL我已經創建了一個DataModule,一個Item對象和類(DoWork)使用這些。這些看起來如下...

public class DataModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind(typeof(IRepository<>)).To<ItemRepository>(); 
    } 

} 

Item對象

public class Item 
{ 

    DAL.IRepository<DAL.Item> _repository; 

    [Inject] 
    public Item(DAL.IRepository<DAL.Item> repository) { 
     _repository = repository; 
    } 

    public List<DAL.Item> GetItems(){ 

     List<DAL.Item> result = new List<DAL.Item>(); 
     result = _repository.GetAll().ToList(); 
     return result;    

    } 

} 

的DoWork的類

public DoWork() 
    { 
     var DataKernel = new StandardKernel(new DataModule());    
     var ItemRepository = DataKernel.Get<IRepository<DAL.Item>>(); 

     Item thisItem = new Item(ItemRepository); 
     List<DAL.Item> myList = thisItem.GetItems(); 
    } 

我的問題是,當我使用此代碼從Web項目我得到一個「DbContext is dispose」運行時錯誤。我試圖保持簡單,只是爲了熟悉框架,但不明白如何獲得正確的DbContext範圍。我已經看過這裏的其他文章,但有一些特定的情況,我想要的基本知識正確。

任何人都可以幫助或指引我在正確的方向嗎?

回答

2

你得到「的DbContext設置」因爲你要丟棄它,你離開GetAll方法之前,您ItemRepository且尚未執行查詢。當調用ToList()時,查詢在GetItems方法內部執行 - 此時由於該關閉,您的數據上下文已經處置。如果您想返回Items作爲IQueryable,則必須讓數據上下文保持活動狀態,直到完成查詢。

我建議在請求範圍內綁定GenericsEntities(ninject會根據您的要求爲您處理)或者在某些自定義範圍內(如果它是桌面應用程序並注入您的存儲庫)。

註冊

Bind<GenericEntities>().ToSelf().InRequestScope(); 

public class ItemRepository : IRepository<Item> 
{ 
    private readonly GenericEntities DB; 

    public ItemRepository(GenericEntities db) 
    { 
     this.DB = db;        
    } 

    public IQueryable<Item> GetAll() 
    { 
     return DB.Set<Item>(); 
    } 
} 
+0

有道理 - 感謝 – TheFrenchDuke

+0

我忘記提及。不要忘記在你的web.config中包含'OnePerRequest'模塊來讓'InRequestScope'正常工作。 – mipe34

+0

建議你在這裏閱讀我的帖子http://www.planetgeek.ch/2012/05/05/what-is-that-all-about-the-repository-anti-pattern/和http://www.planetgeek。 CH/2012/05/08 /所述的倉庫 - 抗圖案澄清/ –

相關問題