我正在使用域驱动设计原则重写我的ASP.NET MVC应用程序.我正在尝试验证我的用户实体.到目前为止,我能够验证基本规则(例如用户名和密码是非null /空格字符串).但是其中一条规则,我需要确保用户名是唯一的.但是我需要访问数据库才能执行此操作,这意味着我必须将IUserRepository注入我的User实体中.
public class User
{
private readonly IUserRepository _userRepository;
public User(IUserRepository repo)
{
_userRepository = repo;
}
public override void Validate()
{
//Basic validation code
if (string.IsNullOrEmpty(Username))
throw new ValidationException("Username can not be a null or whitespace characters");
if (string.IsNullOrEmpty(Password))
throw new ValidationException("Password can not be a null or whitespace characters");
//Complex validation code
var user = _userRepository.GetUserByUsername(Username);
if (user != null && user.id != id)
throw new ValidationException("Username must be unique")
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这似乎......错了.让我的实体依赖于我的存储库似乎是一个坏主意(如果我错了,请纠正我).但是在实体中使用验证代码是有道理的.放置复杂验证码的最佳位置在哪里?