我有兴趣寻找可以改进以下 UnitOfWork 类的使用的方法。 正如您所看到的,它目前没有 UnitOfWork 接口(interface),因此当我在 MVC Controller 中使用它时,我必须创建一个新对象,使我的 Controller 依赖于此类。
我希望能够使用 Ninject 通过将接口(interface)传递给 Controller 的构造函数来注入(inject)此依赖项,我的问题是此类目前不符合开放/关闭原则,我对任何人的建议感兴趣如何改进这一点。我想我还需要某种方式将存储库传递到这个工作单元中,但我不完全确定如何去做。
如有任何帮助,我们将不胜感激,谢谢。
/// <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);
}
}
最佳答案
看来您不希望 UOW 类中存在存储库实例。我认为这篇文章解决了您的问题:Multiple generic repositories in unitofwork?
关于c# - 改进此工作单元类的方法,与开放/封闭原则和依赖注入(inject)/控制反转相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12423546/