【发布时间】:2012-10-18 07:57:07
【问题描述】:
首先很抱歉,如果已经问过这个问题,但我找不到这个“特殊情况”的答案。
我有一个工作单元接口:
public interface IUnitOfWork
{
DbContext Context { get; set; }
void Dispose();
void Save();
}
并使用 Generic Repository 类:
public class GenericRepository<TEntity> where TEntity : class
{
private DbSet<TEntity> dbSet;
private IUnitOfWork UnitOfWork { get; set; }
private DbContext context { get { return UnitOfWork.Context; } }
public GenericRepository(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
我不想在我的 MVC 控制器中执行我的逻辑,所以我添加了一个业务层。 我的问题是,我应该在哪里实例化(和分配)我的 IUnitOfWork,在我的控制器中并将它传递给我的业务层? 示例:
public static class CircleLogic
{
public static void DeleteCircle(IUnitOfWork uow, int id)
{
try
{
var circleRep = new GenericRepository<Circle>(uow);
var circle = circleRep.GetByID(id);
......
circleRep.Delete(id);
uow.Save();
}
catch (Exception ex)
{
throw;
}
}
}
我见过this,但我不想在我的业务层中实例化它。 最好的方法是什么?
谢谢!
【问题讨论】:
-
哼,不知道为什么不行?
-
IMO 这是抽象膨胀的完美案例。如果你已经在使用 ORM,你应该重新考虑你的层,如果你真的需要 IUnitOfWork 和通用存储库。 programmers.stackexchange.com/questions/164000/…
-
@Tom,如果您有构造函数,您也可以注入存储库。
-
@Morten,谢谢,这是我的解决方案之一,创建一个具有 2 个构造函数的非静态类。我真的不需要它,因为它是一个简单的实现,但我试图实现一些东西我从来没有仅仅为了学习而这样做
-
@euphoric,在我的情况下,使用 unitofwork 是完全没用的,因为它是一个简单的网站,但我在几个教程中看到,能够进行 TDD 是一种很好的做法(我会的) t),但理解起来会很有用
标签: c# repository unit-of-work