【发布时间】:2012-02-17 12:59:20
【问题描述】:
我正在使用 UOW 和存储库模式构建一个 Web 应用程序。我对此有基本的了解,我想知道是否应该为项目中的所有表保留一个 UOW 实现,或者根据功能保留一个单独的实现,例如:
public interface IHomeUOW
{
IGenericRepository<User> Users { get; }
IGenericRepository<TableA> Table_A { get; }
IGenericRepository<TableB> Table_B{ get; }
}
public interface IBusinessCaseUOW
{
IGenericRepository<TableA> Table_A { get; }
IGenericRepository<TableXYZ> Table_XYZ{ get; }
}
如您所见,TableA 在 Home UOW 和特定业务案例 UOW 中都可用。一个 UOW 部分实现如下:
public class UnitOfWork : IUnitOfWork
{
private readonly ObjectContext _context;
private UserRepository _userRepository;
public UnitOfWork(ObjectContext Context)
{
if (Context == null)
{
throw new ArgumentNullException("Context wasn't supplied");
}
_context = Context;
}
public IGenericRepository<User> Users
{
get
{
if (_userRepository == null)
{
_userRepository = new UserRepository(_context);
}
return _userRepository;
}
}
}
我的仓库会是这样的
public interface IGenericRepository<T>
where T : class
{
//Fetch records
T GetSingleByRowIdentifier(int id);
T GetSingleByRowIdentifier(string id);
IQueryable<T> FindByFilter(Expression<Func<T, bool>> filter);
// CRUD Ops
void AddRow(T entity);
void UpdateRow(T entity);
void DeleteRow(T entity);
}
public abstract class GenericRepository<T> : IGenericRepository<T>
where T : class
{
protected IObjectSet<T> _objectSet;
protected ObjectContext _context;
public GenericRepository(ObjectContext Context)
{
_objectSet = Context.CreateObjectSet<T>();
_context = Context;
}
//Fetch Data
public abstract T GetSingleByRowIdentifier(int id);
public abstract T GetSingleByRowIdentifier(string id);
public IQueryable<T> FindByFilter(Expression<Func<T, bool>> filter)
{
//
}
//CRUD Operations implemented
}
public class UserRepository : GenericRepository<User>
{
public UserRepository(ObjectContext Context)
: base(Context)
{
}
public override User GetSingleByRowIdentifier(int id)
{
//implementation
}
public override User GetSingleByRowIdentifier(string username)
{
//implementation
}
}
你怎么看?如果这不是 DDD 的 UOW 和 Repository 模式的正确实现,它会因为只是编写一堆代码来抽象对 EF 表的调用而失败吗?
感谢您的宝贵时间..
【问题讨论】:
-
这可能是new codereview stackexchange site 的候选帖子。这不是对 OP 的批评,因为他们可能还没有听说过。
-
显然,OP has 听说过。重复的帖子。
-
嗨,Kurt,实际上我在发完这篇文章后确实看到了另一个网站。现在它有了答案,我不能把它取下来。此外,这个网站似乎获得了更多点击,因为可能没有多少人知道另一个网站,这可以解释为什么那里的浏览量较少且没有答案。
标签: c# asp.net-mvc domain-driven-design repository-pattern unit-of-work