【发布时间】:2014-06-25 09:59:29
【问题描述】:
我目前正在努力实现 IUnitOfwork。 假设我有一个有 2 个方法的接口:
public interface IRepository<TEntity, in TKey>
{
TEntity Get(TKey id);
IQueryable<TEntity> All();
}
现在,假设我有几个实现此接口的类(实体)。 但是,有些实体可能需要额外的查询方法,例如 GetById(int id)。
这可以通过创建一个名为 IRepositoryWithGetById 的新接口轻松解决
public interface IRepository<TEntity, in TKey>
{
TEntity Get(TKey id);
TEntity GetById(int id);
IQueryable<TEntity> All();
}
这将导致维护代码的噩梦。 我正在考虑使用装饰器模式,但我没有找到一个好的解决方案。
注意:我正在使用接口,因为我应该能够模拟它。
根据用户的建议,我正在使用接口继承,所以这里是更新的代码:
public class Wrapper
{
public IRepository standardRepository = new Repository();
public IDeleteRepository deleteRepository = new DeleteRepository();
public ICreateRepository createRepository = new CreateRepository();
}
public class Repository : IRepository
{
public void GetAll() { }
public void GetById(int id) { }
}
public class DeleteRepository : Repository, IDeleteRepository
{
public void Delete() { }
}
public class CreateRepository : Repository, ICreateRepository
{
public void Create() { }
}
public interface IRepository
{
void GetAll();
void GetById(int id);
}
public interface IDeleteRepository : IRepository
{
void Delete();
}
public interface ICreateRepository : IRepository
{
void Create();
}
有谁知道我该如何解决这个问题?
【问题讨论】:
-
接口继承呢?
-
我已经更新了我原来的问题以使用接口继承,但现在这意味着如果我需要一个存储库而不是 GetAll()、GetById()、Create() 那么我需要创建一个名为“DeleteCreateRepository”的类,它将实现 IDeleteRepository 和 ICreateRepository。你明白我的意思吗?
-
为什么不使用扩展方法扩展接口?
-
基本上,在存储库模式中,非常通用的接口应该具有所有基本方法,而不是可以由类实现或由其他接口继承。可以说, IRepository
是最通用的,然后 CustomerRepository 可以从 IRepository 继承所有常见操作。关于Unit of Work,一般会涉及到Save等提交逻辑。 -
感谢您的信息。这正是我目前使用的方法。