0

我一直在处理这个问题一段时间,但似乎仍然无法找到解决方案。我有几个包装 EF 4 ObjectContext 的存储库。下面是一个例子:

public class HGGameRepository : IGameRepository, IDisposable
{
    private readonly HGEntities _context;

    public HGGameRepository(HGEntities context)
    {
        this._context = context;
    }

    // methods

    public void SaveGame(Game game)
    {
        if (game.GameID > 0)
        {
            _context.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Modified);
        }
        else
        {
            _context.Games.AddObject(game);
        }

        _context.SaveChanges();
    }

    public void Dispose()
    {
        if (this._context != null)
        {
            this._context.Dispose();
        }
    }
}

我有以下 NinjectModule:

public class DIModule : NinjectModule
{
    public override void Load()
    {
        this.Bind<HGEntities>().ToSelf();
        this.Bind<IArticleRepository>().To<HGArticleRepository>(); 
        this.Bind<IGameRepository>().To<HGGameRepository>();
        this.Bind<INewsRepository>().To<HGNewsRepository>();
        this.Bind<ErrorController>().ToSelf();
    }
}

由于我使用的是 MVC 2 扩展,因此这些绑定默认为InRequestScope().

我的问题是 ObjectContext 没有得到正确处理。我得到了这里描述的内容:https ://stackoverflow.com/a/5275849/399584 具体来说,我得到一个 InvalidOperationException 状态:

无法定义这两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象。

每次我尝试更新实体时都会发生这种情况。

如果我将我的存储库设置为绑定InSingletonScope()它可以工作,但似乎是个坏主意。

我究竟做错了什么?

编辑:为清楚起见,我只有一个 ObjectContext 我想与每个请求的所有存储库共享。

4

1 回答 1

1

您必须InRequestScope()在模块中指定。根据本文,默认为瞬态,这就是您获得多个上下文的原因。

public class DIModule : NinjectModule
{
    public override void Load()
    {
        this.Bind<HGEntities>().ToSelf().InRequestScope();
        this.Bind<IArticleRepository>().To<HGArticleRepository>().InRequestScope(); 
        this.Bind<IGameRepository>().To<HGGameRepository>().InRequestScope();
        this.Bind<INewsRepository>().To<HGNewsRepository>().InRequestScope();
        this.Bind<ErrorController>().ToSelf().InRequestScope();
    }
}

您是否还通过 nuget 包管理器或旧时尚方式将 ninject 添加到您的项目中?

于 2012-05-09T18:39:52.877 回答