C# 在多层应用程序的DbContext上使用Ninject

C# 在多层应用程序的DbContext上使用Ninject,c#,entity-framework,ninject,dbcontext,n-tier-architecture,C#,Entity Framework,Ninject,Dbcontext,N Tier Architecture,我正在努力了解Ninject,但在这里似乎找不到任何有助于解决我问题的文章。我创建了一个简单的n层解决方案,其中包含Web、业务逻辑和数据访问层。在DAL中,我为我的数据库(简单的双表数据库)和通用存储库(IRepository和ItemRepository)创建了一个模型,如下所示 public interface IRepository<T> where T : class { IQueryable<T> GetAll(); } 项对象 public cl

我正在努力了解Ninject,但在这里似乎找不到任何有助于解决我问题的文章。我创建了一个简单的n层解决方案,其中包含Web、业务逻辑和数据访问层。在DAL中,我为我的数据库(简单的双表数据库)和通用存储库(
IRepository
ItemRepository
)创建了一个模型,如下所示

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

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;            

    }

}
公共类项目
{
DAL.i存储库;
[注入]
公共项目(DAL.i存储库){
_存储库=存储库;
} 
公共列表GetItems(){
列表结果=新列表();
结果=_repository.GetAll().ToList();
返回结果;
}
}
嫁妆班

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();
    }
publicdowork()
{
var DataKernel=新的标准内核(newdatamodule());
var ItemRepository=DataKernel.Get();
Item thisItem=新项目(ItemRepository);
List myList=thisItem.GetItems();
}
我遇到的问题是,当我从Web项目中使用这段代码时,我得到了一个“DbContext被释放”运行时错误。我试图让事情变得简单,只是为了掌握框架,但不知道如何正确地使用
DbContext
范围。我在这里看过其他文章,但都是特定于特定场景的,我希望掌握基本知识

是否有人可以帮助我或为我指出正确的方向?

您得到的是“DbContext已处置”,因为您在离开
ItemRepository
上的
GetAll
方法之前处置了它,并且查询尚未执行。当调用
ToList()
时,查询在
GetItems
方法内执行-此时您的数据上下文已被处置,因为使用了
闭包。如果要将
作为
IQueryable
返回,则必须让数据上下文处于活动状态,直到完成查询

我建议将您的
GenericsEntities
绑定到web应用程序的请求范围(ninject将在请求时为您处理)中,或者绑定到某个自定义范围(如果是桌面应用程序)中,并注入到您的存储库中

注册

Bind<GenericEntities>().ToSelf().InRequestScope();
Bind().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>();
    }   
}
公共类ItemRepository:IRepository
{
专用只读通用实体数据库;
公共项目存储库(通用实体数据库)
{
这个.DB=DB;
} 
公共IQueryable GetAll()
{
返回DB.Set();
}   
}

我忘了提。不要忘了在web.config中包含
OnePerRequest
模块,以使
InRequestScope
正常工作。建议您阅读我在此处发布的文章并
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>();
    }   
}