我很感兴趣寻找可以改进以下 UnitOfWork 类的使用的方法。如您所见,它当前没有 UnitOfWork 接口,因此当我在 MVC 控制器中使用它时,我必须创建一个新对象,使我的控制器依赖于此类。
我希望能够使用 Ninject 通过将接口传递给我的控制器的构造函数来注入这种依赖关系,我的问题是这个类目前不符合打开/关闭原则,我对任何人关于如何改进的建议感兴趣那。我想我还需要某种方式将存储库传递到这个工作单元中,但我不完全确定如何去做。
任何帮助将不胜感激,谢谢。
/// <summary>
/// The unit of work maintains the list of repositories and coordinates changes using the EF CodeFirst data context.
/// This will remove concurrency issues with multiple repositories initialising new contexts within the same HTTP request scope.
/// Instead all transactions are done through the unit of work and that is used to call SaveChanges on the DbContext.
/// </summary>
public class ERSUnitOfWork : IDisposable
{
private ERSDbContext context = new ERSDbContext();
private GenericRepository<Recipe> recipeRepository;
private GenericRepository<Member> memberRepository;
private GenericRepository<Course> courseRepository;
private GenericRepository<Cuisine> cuisineRepository;
private GenericRepository<Review> reviewRepository;
public GenericRepository<Recipe> RecipeRepository
{
get
{
if (this.recipeRepository == null)
{
this.recipeRepository = new GenericRepository<Recipe>(context);
}
return recipeRepository;
}
}
public GenericRepository<Member> MemberRepository
{
get
{
if (this.memberRepository == null)
{
this.memberRepository = new GenericRepository<Member>(context);
}
return memberRepository;
}
}
public GenericRepository<Course> CourseRepository
{
get
{
if (this.courseRepository == null)
{
this.courseRepository = new GenericRepository<Course>(context);
}
return courseRepository;
}
}
public GenericRepository<Cuisine> CuisineRepository
{
get
{
if (this.cuisineRepository == null)
{
this.cuisineRepository = new GenericRepository<Cuisine>(context);
}
return cuisineRepository;
}
}
public GenericRepository<Review> ReviewRepository
{
get
{
if (this.reviewRepository == null)
{
this.reviewRepository = new GenericRepository<Review>(context);
}
return reviewRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
/// <summary>
/// Calls dispose on the DbContext, giving a disposing argument
/// to distinguish from the public Dispose method that is required for the IDisposable interface
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
/// <summary>
/// Calls the custom UnitOfWork Dispose() function instead and tells the garbage collector
/// to suppress finalisation of the object, i.e. freeing up its resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}