您正在尝试重新发明 Repository/UnitOfWork 模式,但这样做并不完全正确。
正确的方法将接近此:
// shared between repositories
public interface IGenericRepository<T>
{
T CreateNew();
void Delete( T item );
void Update( T item );
void Insert( T item );
IEnumerable<T> FindAll();
T FindOne( int id );
}
// specific repositories
public interface IAnimalRepository : IGenericRepository<Animal>
{
IEnumerable<Animal> FindByNumberOfLegs( int NumberOfLegs );
// ... anything specific follows
}
public interface IHumanRepository : IGenericRepository<Human>
{
IEnumerable<Human> FindByGender( Gender gender );
// ... specific repository logic follows
}
// unit of work - a service for clients
public interface IUnitOfWork : IDisposable
{
IAnimalRepository AnimalRepository { get; }
IHumanRepository HumanRepository { get; }
// .. other repositories follow
void SaveChanges();
}
这样,您的服务层依赖于存储库层,您可以轻松地在实现之间切换,例如用于单元测试。你的客户写
// example code
using ( IUnitOfWork uow = new YourImplementationOfUnitOfWork() )
{
var animals = uow.AnimalRepository.FindByNumberOfLegs( 3 );
var person = uow.HumanRepository.CreateNew();
person.Name = "John";
uow.HumanRepository.Insert( person );
uow.SaveChanges();
}
如果您打算限制方法的数量,您可以稍微修改存储库接口:
// shared between repositories
public interface IGenericRepository<T>
{
T CreateNew();
void Delete( T item );
void Update( T item );
void Insert( T item );
IQueryable<T> Query { get; }
}
这样您的客户就可以使用 LINQ:
// example code
using ( IUnitOfWork uow = new YourImplementationOfUnitOfWork() )
{
var animals = uow.AnimalRepository.Query.Where( a => a.NumberOfLegs == 3 );
var person = uow.HumanRepository.CreateNew();
person.Name = "John";
uow.HumanRepository.Insert( person );
uow.SaveChanges();
}