我应该在哪里放DDD独特的检查? [英] Where should I put a unique check in DDD?

查看:216
本文介绍了我应该在哪里放DDD独特的检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作我的第一个DDD的项目,我想我明白实体,数据访问对象,和他们的关系的基本角色。我有一个存储每个验证规则与它相关的实体的基本验证的实现。这工作正常为仅适用于当前实体规则,但需要其他数据时,分崩离析。举例来说,如果我有一个用户名必须是唯一的限制,我想isValid()的调用返回false时,有与当前的名称与现有的用户。

I'm working on my first DDD project, and I think I understand the basic roles of entities, data access objects, and their relationship. I have a basic validation implementation that stores each validation rule with it's associated entity. This works fine for rules that apply to only the current entity, but falls apart when other data is needed. For example, if I have the restriction that a username must be unique, I would like the IsValid() call to return false when there is an existing user with the current name.

不过,我没有找到任何清晰的方式来保持对实体本身这个验证规则。我想对实体的IsNameUnique功能,但大多数解决方案,做到这一点需要我注入了用户的数据访问对象。如果这个逻辑是外部服务?如果是这样,我怎么还留着与实体本身的逻辑?或者是这个东西,应该是用户实体之外吗?

However, I'm not finding any clean way to keep this validation rule on the entity itself. I'd like to have an IsNameUnique function on the entity, but most of the solutions to do this would require me to inject a user data access object. Should this logic be in an external service? If so, how do I still keep the logic with the entity itself? Or is this something that should be outside of the user entity?

谢谢!

推荐答案

我喜欢萨穆埃尔的回应,但是为了简单起见,我建议实施一个规格。您可以创建一个返回boolean,看一个物体满足一定的标准规范。注入的IUserRepository进入规范,检查用户是否已经存在同名,并返回一个布尔结果。

I like Samuel's response, but for the sake of simplicity, I would recommend implementing a Specification. You create a Specification that returns a boolean to see if an object meets certain criteria. Inject an IUserRepository into the Specification, check if a user already exists with that name, and return a boolean result.

public interface ISpecification<T>
{
  bool IsSatisfiedBy(TEntity entity);
}

public class UniqueUsernameSpecification : ISpecification<User>
{
  private readonly IUserRepository _userRepository;

  public UniqueUsernameSpecification(IUserRepository userRepository)
  {
    _userRepository = userRepository;
  }

  public bool IsSatisfiedBy(User user)
  {
    User foundUser = _userRepository.FindUserByUsername(user.Username);
    return foundUser == null;
  }
}

//App code    
User newUser;

// ... registration stuff...

var userRepository = new UserRepository();
var uniqueUserSpec = new UniqueUsernameSpecification(userRepository);
if (uniqueUserSpec.IsSatisfiedBy(newUser))
{
  // proceed
}

这篇关于我应该在哪里放DDD独特的检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆