Domain driven design 我可以调用DDD域服务中的引用unitofwork吗?

Domain driven design 我可以调用DDD域服务中的引用unitofwork吗?,domain-driven-design,Domain Driven Design,如果在发送电子邮件确认之前必须创建并保留用户,则可以在如下域服务中实现此行为: using System; using System.Threading.Tasks; using Monex.Domain.Identity.Aggregates; using Monex.Domain.Identity.Exceptions; using Monex.Domain.Identity.Repository; using Monex.Domain.Identity.SeedWork; nam

如果在发送电子邮件确认之前必须创建并保留用户,则可以在如下域服务中实现此行为:

    using System;
using System.Threading.Tasks;
using Monex.Domain.Identity.Aggregates;
using Monex.Domain.Identity.Exceptions;
using Monex.Domain.Identity.Repository;
using Monex.Domain.Identity.SeedWork;

namespace Monex.Domain.Identity.Services {
    public class UserService {
        readonly IUserConfirmationService _confirmationService;
        readonly IUserRepository _userRepository;
        readonly IUnitOfWork _unitOfWork;
        public UserService (IUserRepository userRepository, IUnitOfWork unitOfWork, IUserConfirmationService confirmationService) {
            _userRepository = userRepository;
            _confirmationService = confirmationService;
            _unitOfWork = unitOfWork;
        }

        public async Task CreateUser (string email, string password, string city) {
            var emailExists = await _userRepository.CheckEmailExists (email);
            if (emailExists)
                throw new EmailAlreadyRegisteredException ();
            var newUser = new User (Guid.NewGuid (), email, password);
            var confirmation = newUser.CreateEmailConfirmation ();
            _userRepository.Add (newUser);
            await _unitOfWork.SaveChanges ();
            await _confirmationService.SendEmail (confirmation);
        }
    }
}

通常采用的机制是不让域服务与基础设施交互——它们通常不处理事务和工作单元。它们与聚合一起属于域模型层,处理通常涉及多个聚合的复杂用例,并且应该没有基础设施问题,包括持久性和通知

应用程序服务应该是完成这项工作的服务。他们应该调用域模型层(服务或聚合),收集更改的项,并将持久性作为事务处理

从您的示例中,您可能应该将
UserService
视为应用程序服务,在
User Aggregate
中调用
factory方法来创建新的用户对象,然后在
存储库的帮助下将其持久化

好的方面是:

  • 我过去使用的一个有趣的模式是将通知(如发送电子邮件)作为工作单元本身的一部分。UoW不仅提交所有数据更改,还负责发送“已注册”通知。您将仅在成功提交后注册/提交通知,并让UoW进行实际发送

  • 更好的模式是发布具有相关细节的事件,并使用订阅者构造和发送通知


通常采用的机制是不让域服务与基础设施交互-它们通常不处理事务和工作单元。它们与聚合一起属于域模型层,处理通常涉及多个聚合的复杂用例,并且应该没有基础设施问题,包括持久性和通知

应用程序服务应该是完成这项工作的服务。他们应该调用域模型层(服务或聚合),收集更改的项,并将持久性作为事务处理

从您的示例中,您可能应该将
UserService
视为应用程序服务,在
User Aggregate
中调用
factory方法来创建新的用户对象,然后在
存储库的帮助下将其持久化

好的方面是:

  • 我过去使用的一个有趣的模式是将通知(如发送电子邮件)作为工作单元本身的一部分。UoW不仅提交所有数据更改,还负责发送“已注册”通知。您将仅在成功提交后注册/提交通知,并让UoW进行实际发送

  • 更好的模式是发布具有相关细节的事件,并使用订阅者构造和发送通知


存储库和发送电子邮件都是基础设施工作,对这些接口(IRepository、IUnitOfWork)的任何调用都应该在应用程序层完成,而不是在域中完成?是的,这是正确的。有助于想象您拥有无限的、永久的RAM内存,并且整个域层始终生活在RAM上。不需要持久性,不需要事务。存储库和发送电子邮件都是基础设施的工作,对这些接口(IRepository、IUnitOfWork)的任何调用都应该在应用程序层完成,而不是在域中完成?是的,这是正确的。有助于想象您拥有无限的、永久的RAM内存,并且整个域层始终生活在RAM上。不需要持久性,不需要事务。