UnitOfWorkとRepositoryパターンのほかにUnityをIoCとして使用したいと思います。いろいろな関連記事や質問を読みましたが、どれも完全に満足するものではありませんでした。私はすべてのアプローチに問題があります。例は私の問題をよりよく説明するでしょう:
2つの別々のクラス(おそらくビジネスサービス)で2つのリポジトリを操作したいのですが、全体的な作業は1つのユニットにまとめられています。
開始点はLocalService1.Method1メソッドです。
public class LocalService1
{
public void Method1(int id)
{
var repository1 = Container.Current.Resolve<IRepository1>(); // Injects the IUnitOfWork for the repository.
var entity1 = repository1.GetEntity1(id);
var service2 = Container.Current.Resolve<LocalService2>(); // Maybe it’s better not to use IoC for business logic. This is not my issue.
service2.Method2(entity1)
}
}
...
public class LocalService2
{
public void Method2(Entity1 entity1)
{
var repository2 = Container.Current.Resolve<IRepository2>(); // Injects the IUnitOfWork for the repository.
var count = repository2.GetEntity2sCount(entity1.Id);
// Do some works with count and entity1
}
}
主な質問は、「LocalService1.Method1を呼び出しているときに、UnitOfWork(ここではObjectContext)をIRepository1とIRepsitory2の間で共有するにはどうすればよいですか?」です。さらに重要なのは、「UnitOfWorkの廃棄について確実にしたい」ということです。
私は答えがこれらの問題に焦点を当てると思います:
- IoC構成
- ライフタイム構成
- 廃棄時間(いつ、どのように?)
「HttpContext」の使用を推奨する場合は、Web以外の環境について検討してください。
私の質問はほとんど「生涯管理」についてですが、徹底的なアプローチを探しています。