我正在努力使用域驱动设计原则重写我的 ASP.NET MVC 应用程序。我正在尝试验证我的用户实体。到目前为止,我能够验证基本规则(例如用户名和密码是非空/空白字符串)。然而规则之一是,我需要确保用户名是唯一的。但是,我需要访问数据库才能执行此操作,这意味着我必须将 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")
}
}
然而这似乎……大错特错。让我的实体依赖于我的存储库似乎是一个坏主意(如果我错了,请纠正我)。但是在实体中包含验证代码是有意义的。放置复杂验证代码的最佳位置在哪里?
我在这些类型的情况下使用的模式是将这种类型的验证逻辑放置在应用程序服务中。在某种程度上,这是有道理的,因为User
实体只对其自身的有效性负责,而不对用户集合的有效性负责。创建用户的应用程序服务方法如下所示:
public User CreateUser(string userName)
{
if (this.userRepository.Exists(userName))
throw new Exception();
var user = new User(userName);
this.userRepository.Add(user);
return user;
}
应用程序服务是一个抽象,无论您是否使用 DDD,它都存在,因此当 DDD 产生摩擦时,它是一个可以回退的好地方。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)