gpt4 book ai didi

c# - DDD 领域模型复杂验证

转载 作者:太空狗 更新时间:2023-10-29 17:33:21 24 4
gpt4 key购买 nike

我正在使用域驱动设计原则重写我的 ASP.NET MVC 应用程序。我正在尝试验证我的用户实体。到目前为止,我能够验证基本规则(比如用户名和密码是非空/空白字符串)。然而,其中一条规则是,我需要确保用户名是唯一的。但是我需要访问数据库才能执行此操作,这意味着我必须像这样将 IUserRepository 注入(inject)到我的用户实体中。

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 出现问题时,它是一个很好的回退点。

关于c# - DDD 领域模型复杂验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11957384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com