Asp.Net MVC 体验 3 业务层的构建

    业务层有80%的代码就是再次包装dal层。软件开发就是不断得消灭重复提高重用。 有个牛人说过:消灭重复的最好办法就是不断的抽象。

    我以前有一篇文章  关于 Repository 在BIZ层的应用  曾经就有了这个想法,但是一直没有实践,直到现在我才发现,当初的这个想法实在太棒了。它也适用于Web Form。

1.来看一下IBaseBiz.cs

public interface IBaseBiz<T>
{
    T Get(object id);
    IQueryable<T> FindAll();
    bool IsExists(Expression<Func<T, bool>> predicate);
    void Add(T entity);
    void Add(List<T> entitys);
    void Delete(T entity);
    void Delete(List<T> entitys);
    void Delete(Expression<Func<T, bool>> predicate);
}

大家会发现这个和IRespository.cs 基本一样,为啥还要重新写个接口呢?

从功能上说确实没什么2样,从职责上区分就有区别的。

2.基类实现BaseBiz<T>

public class BaseBiz<T> : IBaseBiz<T>
{
    protected static readonly ILog logger = LogManager.GetLogger(typeof(BaseBiz<>));
 
    protected IRepository<T> _repository;
 
    public BaseBiz(IRepository<T> repository)
    {
        _repository = repository;
    }
 
    #region IBaseBiz<T> 成员
 
    public T Get(object id)
    {
        return _repository.Get(id);
    }
 
    public IQueryable<T> FindAll()
    {
        return _repository.FindAll();
    }
 
    public bool IsExists(Expression<Func<T, bool>> predicate)
    {
        return _repository.IsExists(predicate);
    }
 
    public void Add(T entity)
    {
        using (IUnitOfWork unitOfWork = KnowDataContext.Begin())
        {
            _repository.Add(entity);
            unitOfWork.Commit();
        }
    }
 
    public void Add(List<T> entitys)
    {
        _repository.Add(entitys);
    }
 
    public void Delete(T entity)
    {
        _repository.Delete(entity);
    }
 
    public void Delete(List<T> entitys)
    {
        _repository.Delete(entitys);
    }
 
    public void Delete(Expression<Func<T, bool>> predicate)
    {
        using (IUnitOfWork unitOfWork = KnowDataContext.Begin())
        {
            _repository.Delete(predicate);
            unitOfWork.Commit();
        }
    }
    #endregion
}

吧所有的简单封装dal层的代码全部都抽象到这个基类了。这样具体的业务类就只负责复杂业务逻辑了,类变得干净了,重复代码也消灭了。

3.业务类QuestionBiz

public class QuestionBiz : BaseBiz<Question>
{
 
    public QuestionBiz(IRepository<Question> repository)
        : base(repository)
    {
 
    }
 
    public IQueryable<Question> GetQuestionByUser(string userId)
    {
        return _repository.FindAll().GetQuestionByUser(userId);
    }
}

来看一下方法调用的顺序

irepository->linqrepository->ibasebiz->basebiz->questionbiz

basebiz不能像linqrepository那样吧数据访问抽象在一个类中。业务逻辑是灵活的,根据需求会不断的变化,所以需要有像questionbiz这样的具体业务类去实现。这就是事物都具有2面性,共性和特性。共性我们可以抽象成basebiz,特性就要实现一个继承基类又有其独特变化的实现类。

原文地址:https://www.cnblogs.com/yuanhuaming/p/1677082.html