我正試圖與Ninject握手,似乎無法找到任何有助於解決問題的文章。我創建了一個簡單的包含Web,業務邏輯和數據訪問層的n層解決方案。在DAL中,我爲我的數據庫(簡單的兩個表格數據庫)和通用存儲庫(IRepository
和ItemRepository
)創建了一個模型,如下所示。在多層應用程序的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
範圍。我已經看過這裏的其他文章,但有一些特定的情況,我想要的基本知識正確。
任何人都可以幫助或指引我在正確的方向嗎?
有道理 - 感謝 – TheFrenchDuke
我忘記提及。不要忘記在你的web.config中包含'OnePerRequest'模塊來讓'InRequestScope'正常工作。 – mipe34
建議你在這裏閱讀我的帖子http://www.planetgeek.ch/2012/05/05/what-is-that-all-about-the-repository-anti-pattern/和http://www.planetgeek。 CH/2012/05/08 /所述的倉庫 - 抗圖案澄清/ –