Joh*_*ohn 3 c# inheritance abstract-class repository-pattern
我正在为MVC 2 Web应用程序编写EF4数据层,我需要有关选择继承与抽象基类的建议.我的存储库在'generic repo'结构之后运行良好,但现在我想添加"Audit"功能,该功能在每次执行CRUD操作时都会记录.
这是我到目前为止使用的合同:
public interface IRepository<T>
{
void Create(T entity);
void Update(T entity);
void Delete(Func<T, bool> predicate);
T Get(Func<T, bool> predicate);
IQueryable<T> Query();
}
Run Code Online (Sandbox Code Playgroud)
我的回购 实现看起来像这样:
sealed class EFRepository<TEntity> : IRepository<TEntity>
where TEntity : EntityObject
{
ObjectContext _context;
ObjectSet<TEntity> _entitySet;
public EFRepository(ObjectContext context)
{
_context = context;
_entitySet = _context.CreateObjectSet<TEntity>();
}
public void Create(TEntity entity)
{
_entitySet.AddObject(entity);
_context.SaveChanges();
}
public void Update(TEntity entity)
{
_entitySet.UpdateObject(entity);
_context.SaveChanges();
}
public void Delete(Func<TEntity, bool> predicate)
{
TEntity entity = _entitySet.Single(predicate);
_entitySet.DeleteObject(entity);
_context.SaveChanges();
}
public TEntity Get(Func<TEntity, bool> predicate)
{
return _entitySet.SingleOrDefault(predicate);
}
public IQueryable<TEntity> Query()
{
return _entitySet;
}
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个概念AuditableRepository<T>.我应该像这样创建它:
interface IAuditable<T>
interface IRepository<T>
AuditableRepository<T> : IRepository<T>, IAuditable<T>
EFRepository<T> : AuditableRepository<T>
Run Code Online (Sandbox Code Playgroud)
或者像这样更好:
interface IAuditable<T>
interface IRepository<T>
EFRepository<T> : IRepository<T>, IAuditable<T>
Run Code Online (Sandbox Code Playgroud)
甚至:
interface IAuditable<T>
interface IRepository<T>
AuditableRepository<T> : IRepository<T>, IAuditable<T>
EFRepository<T> : IRepository<T>
AuditableEFRepository<T> : AuditableRepository<T>
Run Code Online (Sandbox Code Playgroud)
并非所有的EFRepositories都需要审核.我该怎么办?
这是另一种可能性(使用Decorator对象向现有存储库添加其他功能):
public sealed class Auditor<T> : IRepository<T>
{
private readonly IRepository<T> _repository;
public Auditor(IRepository<T> repository)
{
_repository = repository;
}
public void Create(T entity)
{
//Auditing here...
_repository.Create(entity);
}
//And so on for other methods...
}
Run Code Online (Sandbox Code Playgroud)
使用Decorator添加其他功能的好处是,它可以避免在您考虑使用审计的某些存储库时开始看到的组合爆炸,有些没有,有些使用EF,有些则没有.每一个可能适用或可能不适用的新功能都会逐渐变得更糟,通常最终会转变为配置标志和混乱的内部分支.
| 归档时间: |
|
| 查看次数: |
1289 次 |
| 最近记录: |