EF DbContext和Ninject

4

我之前问了一个关于为什么默认的等值比较器在我合并两个实体集合时似乎不起作用的问题。

EF Code First - Linq to Entities Union EqualityComparer

答案是因为我使用了两个不同的DbContext实例,因此引用不同。

现在,我正在尝试在请求中共享我的DbContent。我看到一些“复杂”的示例,但我想尝试更简单的解决方案。

所以我创建了一个IDbContext接口,其中简单地概述了我的实体。

public interface IDbContext {
   int SaveChanges();
   DbSet<News> News { get; set; }
   DbSet<Category> Categories { get; set; }
}

我的 DbContext 实现如下:

public class SiteContext : DbContext, IDbContext {
   public DbSet<News> News { get; set; }
   public DbSet<Category> Categories { get; set; }

   protected override void OnModelCreating(DbModelBuilder modelBuilder) {
      ...
   }
}

那么在我的两个存储库(NewsRepository 和 CategoryRepository)中,我将 IDbContext 作为构造函数参数。

IDbContext _db;

public NewsRepository(IDbContext db) {
    _db = db;
}

所以现在我假设如果我将IDbContext绑定到请求范围中的SiteContext,我的存储库将共享相同的上下文?
 kernel.Bind<IDbContext>().To<SiteContext>().InRequestScope();

然而,当我尝试使用之前问题中的联合查询时,仍然会收到重复的实体!我做错了什么?我如何确定在一个请求中确实使用了相同的上下文?


你可以在上下文的构造函数中设置断点吗?我正在使用相同的方法,就像你一样,每个请求都使用一个上下文。 - Gluip
2个回答

5
因为每个存储库构建时,Ninject都会为您提供一个新的SiteContext实例。这就是为什么它不起作用的原因。最好使用UnitOfWork实现,这意味着所有存储库都使用相同的上下文。
UnitOfWork在构造时将接收IDbContext。
类似以下内容即可:
private IDbContext _context;

public UnitOfWork(IDbContext context)
{
    _context = context
}

private _INewsRepository;
public INewsRepoitory 
{
    get{
         if(_INewsRepository == null)
         {
              _INewsRepository = new NewsREpository(_context);
              return _INewsRepository;
         }
         else
         {
              return _INewsRepository;
         }    
}

-1
为了改进feanz的解决方案,我仍然会使用Ninject进行INewsRepository的属性注入:
[Inject]
public INewsRepository NewsRepo {get;set;}

每次创建 IUnitOfWork 时,也会创建一个 INewsRepository。这仍然需要添加到您的 Ninject 绑定中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接