【问题标题】:Using Ninject on the DbContext of a multi-tier application在多层应用程序的 DbContext 上使用 Ninject
【发布时间】:2013-01-04 16:04:15
【问题描述】:

我正在尝试掌握 Ninject,但似乎无法在此处找到任何有助于解决我的问题的文章。我创建了一个简单的 n 层解决方案,其中包含 Web、业务逻辑和数据访问层。在 DAL 中,我为我的数据库(简单的两个表 DB)和通用存储库(IRepositoryItemRepository)创建了一个模型,如下所示。

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 已处置”运行时错误。我试图让事情变得简单,只是为了掌握框架,但不明白如何让DbContext 范围正确。我已经查看了这里的其他文章,但所有文章都针对某些场景,我想掌握正确的基础知识。

谁能帮助或指出正确的方向?

【问题讨论】:

    标签: c# entity-framework ninject dbcontext n-tier-architecture


    【解决方案1】:

    您得到“DbContext 已处置”,因为您在将 GetAll 方法留在 ItemRepository 上之前处置它,并且查询尚未执行。当ToList() 被调用时,查询在GetItems 方法内执行——那时你的数据上下文已经被释放,因为using 闭包。如果您想将Items 作为IQueryable 返回,则必须让数据上下文处于活动状态,直到您完成查询。

    我建议将您的 GenericsEntities 绑定到 Web 应用程序的请求范围内(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>();
        }   
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多