Linq to SQL の Repository パターンを実装する例はたくさんあるようです。それらのほとんどは IRepository と DI を備えています。Unit of Work を実装しているものと実装していないものがあります。SO と Google on Linq で検索して返された結果のほとんどを SQL リポジトリ パターンに読み込もうとしました。それにもかかわらず、私はまだ完全な解決策に出くわしていません。
私の読書から、以下に示すようにリポジトリパターンを実装しました:
(出典:sites.google.comのbaburajpb)
DI を使用して、リポジトリが依存するインターフェイスを登録しています。
this.container.RegisterType<IConnectionStringFactory, ConnectionStringFactory>(new ContainerControlledLifetimeManager(),
new InjectionConstructor(connectionString));
this.container.RegisterType<IDataContextFactory, DataContextFactory>();
リポジトリ パターンの実装:
public interface IPrivilegeRepository : IRepository<PrivilegesEntity>
{
IList<MenuModel> GetRootMenu();
IList<MenuModel> GetChildMenu(int parentId);
}
public class PrivilegeRepository : Repository<PrivilegesEntity>, IPrivilegeRepository
{
#region IPrivilegeRepository Members
public IList<MenuModel> GetRootMenu()
{
return FindAll(menu => menu.ParentId == null)
.OrderBy(menu => menu.SortOrder)
.Select(c => EntityMapper.Privileges.ToBusinessObject(c))
.ToList();
}
public IList<MenuModel> GetChildMenu(int parentId)
{
return FindAll(menu => menu.ParentId == parentId)
.OrderBy(menu => menu.SortOrder)
.Select(menu => EntityMapper.Privileges.ToBusinessObject(menu))
.ToList();
}
#endregion
public PrivilegeRepository(IDataContextFactory dataContextFactory)
: base(dataContextFactory)
{
}
}
IRepository ジェネリック インターフェイス:
public interface IRepository<T> where T : class
{
IEnumerable<T> All();
IEnumerable<T> FindAll(Expression<Func<T, bool>> exp);
T Single(Expression<Func<T, bool>> exp);
T First(Expression<Func<T, bool>> exp);
}
リポジトリ クラスは、以下のように IRepository の実装 (表示されていません) で実装され、DI が処理している IDataContextFactory に依存しています。
public class Repository<T> : IRepository<T> where T : class
{
public Repository(IDataContextFactory dataContextFactory)
{
this.dataContextFactory = dataContextFactory;
}
}
リポジトリは IoC を使用して消費されます。
PrivilegeRepository repository = container.Resolve<PrivilegeRepository>();
リポジトリを使用するアプリケーション層で Linq から SQL への依存を避けるために、クエリの結果をビジネス オブジェクトのコレクションとして返しています。上記のシナリオは、MVVM パターンを使用している私の WPF アプリケーションで正常に動作します。Linq-SQL によって生成されたクラスに依存しない ViewModel aks Presenter クラスがあります。
データをデータベースに保存できるように、このパターンを拡張するにはどうすればよいですか。ビジネス オブジェクトをリポジトリに戻して保存したいと考えています。出来ますか?このようなシナリオで Unit of Work を実装するにはどうすればよいですか。