加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#存储库设计问题

发布时间:2020-12-15 23:56:34 所属栏目:百科 来源:网络整理
导读:我正在为MVC 2 Web应用程序编写EF4数据层,我需要有关选择继承与抽象基类的建议.我的存储库在’generic repo’结构之后运行良好,但现在我想添加“Audit”功能,该功能在每次执行CRUD操作时都会记录. 这是我到目前为止使用的合同: public interface IRepositor
我正在为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();
}

我的回购实现看起来像这样:

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;
    }
}

我想创建AuditableRepository< T>的概念.我应该像这样创建它:

interface IAuditable<T>
interface IRepository<T>
AuditableRepository<T> : IRepository<T>,IAuditable<T>
EFRepository<T> : AuditableRepository<T>

或者像这样更好:

interface IAuditable<T>
interface IRepository<T>
EFRepository<T> : IRepository<T>,IAuditable<T>

甚至:

interface IAuditable<T>
interface IRepository<T>
AuditableRepository<T> : IRepository<T>,IAuditable<T>
EFRepository<T> : IRepository<T>
AuditableEFRepository<T> : AuditableRepository<T>

并非所有的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...
}

使用Decorator添加其他功能的好处是,它可以避免在您考虑使用审计的某些存储库时开始看到的组合爆炸,有些没有,有些使用EF,有些则没有.每一个可能适用或可能不适用的新功能都会逐渐变得更糟,通常最终会转变为配置标志和混乱的内部分支.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读