似乎有很多关于实现Linq to SQL的Repository模式的示例。其中大多数都具有IRepository和DI;有些已经实施了工作单位,有些则没有。我尝试将大部分由SO和Google上的搜索返回的结果阅读为从Linq到SQL存储库模式。尽管如此,我还没有遇到完整的解决方案。Linq to SQL使用IoC,依赖注入,工作单元的存储库模式
从我读,我实现了一个存储库模式,如下图所示:
我使用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(未示出)的实施方式中,并具有上IDataContextFactory依赖性其中DI正在的护理:
public class Repository<T> : IRepository<T> where T : class
{
public Repository(IDataContextFactory dataContextFactory)
{
this.dataContextFactory = dataContextFactory;
}
}
存储库被消耗使用IoC:
PrivilegeRepository repository = container.Resolve<PrivilegeRepository>();
我将查询的结果作为Business Object的集合返回以避免依赖Lin q到我使用存储库的应用程序层上的SQL。上述场景适用于使用MVVM模式的WPF应用程序。我有ViewModel aks Presenter类,它们不依赖Linq-SQL生成的类。
如何扩展此模式以便将数据保存到数据库。我想将Business Objects传递回存储库并保存它们。可能吗?如何在这种情况下实施工作单元。
你可能想看看活动记录模式;它涵盖了完整的CRUD操作以及类似存储库的查询访问功能。 – 2009-10-26 11:19:54
与VS2010一起发布的实体框架如何? – Raj 2009-11-08 05:55:44
@Raj我想你错过了他想成为ORM独立的事实。 – Novus 2012-07-26 17:36:20