MVC5 + EF + UOW +服务层在哪里调用SaveChanges()并避免多次访问DB?

时间:2014-07-07 17:25:00

标签: c# design-patterns asp.net-mvc-5 entity-framework-6 unit-of-work

我正在构建一个Web应用程序,使用: MVC5 EF Code First 存储库工作单元模式。直到现在我有3层:

  • “数据层”,其中包含存储库,UOW。
  • “服务层”,它引用了UOW来实现业务逻辑和业务验证。
  • “Web Layer”,负责通过与服务层通信来显示数据。

我的域/业务对象在另一个项目中分开。所以基本上我跟随John Papa CodeCamper结构,除了添加“服务层”。

数据/合同/ IRepository.cs

public interface IRepository<T> where T : class
{
    IQueryable<T> GetAll();
    T GetById(int id);
    void Add(T entity);
    void Update(T entity);
    void Delete(T entity);
    void Delete(int id);
}

数据/合同/ IUnitOfWork.cs

public interface IUnitOfWork
{
    // Save pending changes to the data store.
    void Commit();

    // Repositories
    IRepository<Event> Events { get; }
    IRepository<Candidate> Candidates { get; }
}

数据/ EFRepository.cs

/// <summary>
/// The EF-dependent, generic repository for data access
/// </summary>
/// <typeparam name="T">Type of entity for this Repository.</typeparam>
public class EFRepository<T> : IRepository<T> where T : class
{
    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

    protected DbContext DbContext { get; set; }

    protected DbSet<T> DbSet { get; set; }

    public virtual IQueryable<T> GetAll()
    {
        return DbSet;
    }

    public virtual T GetById(int id)
    {
        //return DbSet.FirstOrDefault(PredicateBuilder.GetByIdPredicate<T>(id));
        return DbSet.Find(id);
    }

    public virtual void Add(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Detached)
        {
            dbEntityEntry.State = EntityState.Added;
        }
        else
        {
            DbSet.Add(entity);
        }
    }

    public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State == EntityState.Detached)
        {
            DbSet.Attach(entity);
        }
        dbEntityEntry.State = EntityState.Modified;
    }

    public virtual void Delete(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Deleted)
        {
            dbEntityEntry.State = EntityState.Deleted;
        }
        else
        {
            DbSet.Attach(entity);
            DbSet.Remove(entity);
        }
    }

    public virtual void Delete(int id)
    {
        var entity = GetById(id);
        if (entity == null) return; // not found; assume already deleted.
        Delete(entity);
    }
}

数据/ UnitOfWork.cs

/// <summary>
/// The "Unit of Work"
///     1) decouples the repos from the controllers
///     2) decouples the DbContext and EF from the controllers
///     3) manages the UoW
/// </summary>
/// <remarks>
/// This class implements the "Unit of Work" pattern in which
/// the "UoW" serves as a facade for querying and saving to the database.
/// Querying is delegated to "repositories".
/// Each repository serves as a container dedicated to a particular
/// root entity type such as a <see cref="Url"/>.
/// A repository typically exposes "Get" methods for querying and
/// will offer add, update, and delete methods if those features are supported.
/// The repositories rely on their parent UoW to provide the interface to the
/// data layer (which is the EF DbContext in this example).
/// </remarks>
public class UnitOfWork : IUnitOfWork, IDisposable
{
    public UnitOfWork(IRepositoryProvider repositoryProvider)
    {
        CreateDbContext();

        repositoryProvider.DbContext = DbContext;
        RepositoryProvider = repositoryProvider;       
    }

    // Repositories
    public IRepository<Student> Students { get { return GetStandardRepo<Event>(); } }
    public IRepository<Course> Courses { get { return GetStandardRepo<Course>(); } }

    /// <summary>
    /// Save pending changes to the database
    /// </summary>
    public void Commit()
    {
        //System.Diagnostics.Debug.WriteLine("Committed");
        DbContext.SaveChanges();
    }

    protected void CreateDbContext()
    {
        DbContext = new UnicornsContext();

        // Do NOT enable proxied entities, else serialization fails
        DbContext.Configuration.ProxyCreationEnabled = false;

        // Load navigation properties explicitly (avoid serialization trouble)
        DbContext.Configuration.LazyLoadingEnabled = false;

        // Because Web API will perform validation, I don't need/want EF to do so
        DbContext.Configuration.ValidateOnSaveEnabled = false;
    }

    protected IRepositoryProvider RepositoryProvider { get; set; }

    private IRepository<T> GetStandardRepo<T>() where T : class
    {
        return RepositoryProvider.GetRepositoryForEntityType<T>();
    }
    private T GetRepo<T>() where T : class
    {
        return RepositoryProvider.GetRepository<T>();
    }

    private UnicornsContext DbContext { get; set; }

    #region IDisposable

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (DbContext != null)
            {
                DbContext.Dispose();
            }
        }
    }

    #endregion
}

然后最终使用Ninject来解决依赖:

kernel.Bind<RepositoryFactories>().To<RepositoryFactories>().InSingletonScope();
kernel.Bind<IRepositoryProvider>().To<RepositoryProvider>();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>();

我应该在哪里调用UOW.Commit(),以便我可以在其他服务中重用特定服务的已实现逻辑,而不是再次重写它?

  1. 控制器是否应该用于提交更改?
  2. 或者服务本身应该提交更改吗?
  3. 到目前为止,我已阅读Stack Overflow,选项(1)更简单,但违反了单一责任原则,或者如果我想与移动/桌面应用程序集成则会出现这种情况。

    选项(2):此处我 必须 在每个服务函数调用中调用commit,因此我将无法重用函数因为这可能导致多次前往DB。

1 个答案:

答案 0 :(得分:0)

在我的项目中,我在控制器中调用Save(),因为我想尽可能多地重用我的方法,并且当他们自己调用Save()时,很难将多个方法“粘合”在一起。 更糟糕的是,如果控制器级别存在错误,您可能希望避免调用save(),例如某种方法会创建一堆小对象,这些小对象在必须提交的主对象中使用。同时提交两者似乎比createSMallObject()和createMasterObject()中的hardocded提交更好,以防万一发生。