对我来说,仓库格局即将把一个简单包装的数据访问方法。 LINQ to SQL在你的情况下,但NHibernate,在其他人手里滚动。我发现自己在做的是创建一个每个表的存储库,因为这非常简单(就像bruno列表和你已经拥有的那样)。这是负责寻找事情和做CRUD操作。
但是,我有一个服务级别,可以处理更多的聚合根,就像Johannes提到的那样。我会有一个像GetExistingUser(int id)方法的UserService。这将在内部调用UserRepository.GetById()方法来检索用户。如果您的业务流程需要由GetExistingUser()返回的用户类几乎总是需要填充User.IsInRoles()属性,那么只需使用UserService依赖于UserRepository 和 RoleRepository。在伪代码可能是这个样子:
public class UserService
{
public UserService(IUserRepository userRep, IRoleRepository roleRep) {...}
public User GetById(int id)
{
User user = _userService.GetById(id);
user.Roles = _roleService.FindByUser(id);
return user;
}
的userRep和roleRep将与您的LINQ到SQL构造位是这样的:
public class UserRep : IUserRepository
{
public UserRep(string connectionStringName)
{
// user the conn when building your datacontext
}
public User GetById(int id)
{
var context = new DataContext(_conString);
// obviously typing this freeform but you get the idea...
var user = // linq stuff
return user;
}
public IQueryable<User> FindAll()
{
var context = // ... same pattern, delayed execution
}
}
个人而言,我会做仓库类在内部作用域并且公开UserService和其他XXXXXService类,以便让服务API的使用者保持诚实。我再次看到存储库与与数据存储库交谈的行为更紧密地联系在一起,但您的服务层更紧密地与业务流程的需求保持一致。
我经常发现自己得太多真中的LINQ到对象的灵活性和所有的东西和使用的IQuerable 等而不是吐出什么,我真正需要的只是建立服务方法。用户LINQ在适当的情况下,但不要试图让仓库做所有事情。
public IList<User> ActiveUsersInRole(Role role)
{
var users = _userRep.FindAll(); // IQueryable<User>() - delayed execution;
var activeUsersInRole = from users u where u.IsActive = true && u.Role.Contains(role);
// I can't remember any linq and i'm type pseudocode, but
// again the point is that the service is presenting a simple
// interface and delegating responsibility to
// the repository with it's simple methods.
return activeUsersInRole;
}
所以,这有点漫不经心。不确定我是否真的帮助过任何人,但我的建议是避免使用扩展方法太过花哨,只需添加另一层,以保证每个移动部件都非常简单。适用于我。
不,每个存储库应该封装一个聚合根的持久性逻辑 – 2009-08-03 20:47:11
@Johannes是的,但是如何? – 2009-08-03 23:27:28