ebr*_*lil 5 c# design-patterns unit-of-work entity-framework-6 asp.net-mvc-5
我正在使用以下内容构建Web应用程序:MVC5和EF Code First with Repository和Unit of Work Patterns.直到现在我有3层:
我的域/业务对象在另一个项目中分开.所以基本上我遵循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);
}
Run Code Online (Sandbox Code Playgroud)
数据/合同/ IUnitOfWork.cs
public interface IUnitOfWork
{
// Save pending changes to the data store.
void Commit();
// Repositories
IRepository<Event> Events { get; }
IRepository<Candidate> Candidates { get; }
}
Run Code Online (Sandbox Code Playgroud)
数据/ 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);
}
}
Run Code Online (Sandbox Code Playgroud)
数据/ 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
}
Run Code Online (Sandbox Code Playgroud)
然后最终使用Ninject来解决依赖:
kernel.Bind<RepositoryFactories>().To<RepositoryFactories>().InSingletonScope();
kernel.Bind<IRepositoryProvider>().To<RepositoryProvider>();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
Run Code Online (Sandbox Code Playgroud)
我应该在哪里调用,UOW.Commit()以便我可以在其他服务中重用特定服务的实现逻辑,而不是重新编写它?
到目前为止,我已经阅读了Stack Overflow,选项(1)更简单但违反了单一责任原则,或者如果我想与移动/桌面应用程序集成则会出现这种情况.
选项(2):这里我必须在每个服务函数调用中调用commit,因此我将无法重用函数,因为这可能导致多次访问DB.
在我的项目中,我在控制器中调用 Save(),因为我想尽可能地重用我的方法,并且当它们自己调用 Save() 时,将多个方法“粘合”在一起是很困难的。更糟糕的是,如果控制器级别出现错误,您可能希望避免调用 save(),例如某些方法创建了一堆小对象,这些对象在必须提交的主对象中使用。同时提交两者似乎比在 createSMallObject() 和 createMasterObject() 中进行硬编码提交更好,以防中间发生某些情况。
| 归档时间: |
|
| 查看次数: |
875 次 |
| 最近记录: |