MVC分层项目结构

时间:2013-09-06 12:47:04

标签: c# entity-framework asp.net-mvc-4 design-patterns architecture

我们正在使用C#/ MVC 4和Entity Framework 5开始一个新的Web项目进行数据访问。我决定采用n层方法来完成项目结构,我想对我的设计决策提出一些反馈。

这就是解决方案的结构:

Project.Model(类库):包含EF .edmx,实体模型和视图模型

Project.DAL(类库):包含EF DbContext和Repository类

Project.BLL(类库):包含业务逻辑类

项目(MVC项目)

DAL

数据访问层仅关注简单的CRUD操作。我决定采用存储库方法。以下是Repository接口:

public interface IRepository
{
}

public interface IRepository<T> : IRepository, IDisposable 
    where T : class, new()
{
    T Add(T item);

    T Get(object id);

    T Get(Expression<Func<T, bool>> predicate);

    IQueryable<T> GetAll();

    IQueryable<T> GetAll(Expression<Func<T, bool>> predicate);

    void Update(T item);

    void Delete(T item);
}

在对Web项目中使用Entity Framework进行一些研究之后,普遍的共识是每个请求应该只有一个DbContext / ObjectContext。因此,为了为每个请求创建和处理单个上下文,我编写了一个HttpModule,它将DbContext注入到HttpContext中。

public class DbContextModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += context_BeginRequest;
        context.EndRequest += context_EndRequest; 
    }

    public void Dispose()
    {
    }

    private void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext httpContext = application.Context;

        httpContext.Items.Add(Repository.ContextKey, new ProjectEntities());
    }

    private void context_EndRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext httpContext = application.Context;

        var entities = (ProjectEntities)httpContext.Items[Repository.ContextKey];

        entities.Dispose();
        entities = null;

        application.Context.Items.Remove(Repository.ContextKey);
    }
}

接下来是Repository基类。请注意,构造函数使用上面的HttpModule注入的DbContext

public abstract class Repository<T> : IRepository<T> where T : class, new()
{
    protected Repository()
    {
        if (HttpContext.Current == null)
        {
            throw new Exception("Cannot create repository - current HttpContext is null.");
        }

        _entities = (ProjectEntities)HttpContext.Current.Items[Repository.ContextKey];

        if (_entities == null)
        {
            throw new Exception("Cannot create repository - no DBContext in the current HttpContext.");
        }
    }

    private ProjectEntities _entities;

    public T Add(T item)
    {
        _entities.Set<T>().Add(item);
        _entities.SaveChanges();

        return item;
    }

    public T Get(object id)
    {
        return _entities.Set<T>().Find(id);
    }

    public T Get(Expression<Func<T, bool>> predicate)
    {
        return _entities.Set<T>().AsQueryable().FirstOrDefault(predicate);
    }

    public IQueryable<T> GetAll()
    {
        return _entities.Set<T>().AsQueryable();
    }

    public IQueryable<T> GetAll(Expression<Func<T, bool>> predicate)
    {
        return _entities.Set<T>().AsQueryable().Where(predicate);
    }

    public void Update(T item)
    {
        _entities.Entry(item).State = EntityState.Modified;
        _entities.SaveChanges();
    }

    public void Delete(T item)
    {
        _entities.Set<T>().Remove(item);
        _entities.SaveChanges();
    }
}

一个简单的实施例子......

public class AdminRepository : Repository<Admin>
{
    public Admin GetByEmail(string email)
    {
        return Get(x => x.Email == email);
    }
}

BLL

业务逻辑层封装了所有业务逻辑。为了保持约束,我写了这样的基础“逻辑”类:

public abstract class Logic<TRepository> where TRepository : class, IRepository, new()
{
    private static Expression<Func<TRepository>> _x = () => new TRepository();
    private static Func<TRepository> _compiled = _x.Compile(); 

    protected Logic()
    {
        Repository = _compiled();
    }

    protected internal TRepository Repository { get; private set; }
}

构造函数自动创建所需的Repository类,因此子类中不需要额外的代码来实例化存储库。这是一个简单的实现示例

public class AdminLogic : Logic<AdminRepository>
{
    public Admin Add(Admin admin)
    {
        return Repository.Add(admin);
    }

    public Admin Get(object id)
    {
        return Repository.Get(id);
    }

    public Admin GetByEmail(string email)
    {
        return Repository.GetByEmail(email);
    }

    public IQueryable<Admin> GetAll()
    {
        return Repository.GetAll();
    }

    public void Update(Admin admin)
    {
        Repository.Update(admin);
    }
}

此示例更多是DAL存储库的传递,但稍后添加业务逻辑不会成为问题。我选择从BLL返回IQueryable,因为我们正在使用一些需要IQueryable来延迟执行的第三方工具。

项目(MVC项目)

现在最后这里是一个简单的控制器动作:

public ActionResult Index(int? page)
{
    // Instantiate logic object
    AdminLogic logic = new AdminLogic();

    // Call GetAll() and use AutoMapper to project the results to the viewmodel
    IQueryable<AdminModel> admins = logic.GetAll().Project().To<AdminModel>();

    // Paging (using PagedList https://github.com/TroyGoode/PagedList)
    IPagedList<AdminModel> paged = admins.ToPagedList(page ?? 1, 25);

    return View(paged);
}

一切都按预期工作,测试显示EF上下文得到妥善处理,整体速度也很好。

这是一个很好的方法吗?

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

我认为如果您打算使用存储库模式,您应该将您的存储库视为aggregates对我来说,做存储库可以有一定程度的抽象,这很好,但这样做可能导致存储库成为以实体为中心,有时难以沟通与属于同一聚合根的其他对象

前段时间我遇到了这个困境,而不是使用存储库(T)我最终在“通用存储库”中使用了方法(T),这使我对使用属于聚合的其他对象的操作更加轻松root(我这样做是因为这对我很好,但这并不意味着这对你很好,我把这个例子放到桌子上只是为了你考虑它),你可以看看{我发现{3}}和this quesion非常有趣。

杰里米·米勒谈到如何实施this article

public interface IRepository { // Find an entity by its primary key // We assume and enforce that every Entity // is identified by an "Id" property of // type long T Find<T>(long id) where T : Entity; // Query for a specific type of Entity // with Linq expressions. More on this later 
IQueryable<T> Query<T>(); 
IQueryable<T> Query<T>(Expression<Func<T, bool>> where); // Basic operations on an Entity 
void Delete(object target); 
void Save(object target); 
void Insert(object target); 
T[] GetAll<T>(); }

这与您在回购邮件中所做的非常相似。

可能,我认为还需要2层(取决于您的要求),一个是IRepository来处理应用程序中的常见操作或操作,也可能是组件的另一层(电子邮件,日志,缓存管理器) ,密码学,助手等)

关于你如何处理BL的逻辑看起来像是对我来说太过分了,实际上你将这些存储库耦合到我认为没那么好的逻辑中。

尝试在您的应用中实施services,因为您可以从中获得一些好处。

假设您要创建一个具有BL

登录方法的UserService
public class UserService:IService {
    public UserService(IUserRepository, IMailer, ILogger){
      // for example you can follow the next use case in your BL
      // try to login, if failed reteat after 3 time you block the accunt and send a mail

    }

   public bool login(string username, string password){
   }

}

然后你可以在你的控制器中实现该服务(如果你正在使用容器并且只是调用登录服务,则将它注入构造函数中),这将使你的实现更加清晰

public ActionResult Index(){
  //then you're going to be able to use  _userService.login()
}

这样你就会有一个Dependency Injection,理论上它更容易维护。

只是我的两分钱