私はしばらくこの問題に取り組んできましたが、まだ解決策が見つからないようです。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 を取得します。
2 つのオブジェクトが異なる ObjectContext オブジェクトに関連付けられているため、2 つのオブジェクト間の関係を定義できません。
これは、エンティティを更新しようとするたびに発生します。
リポジトリをバインドするように設定するInSingletonScope()
と機能しますが、悪い考えのようです。
私は何を間違っていますか?
編集:明確にするために、リクエストごとにすべてのリポジトリと共有したい ObjectContext を1つだけ持っています。