如何在域驱动设计中使用具有较大聚合的工厂方法?

How to use Factory methods with larger aggregates in Domain Driven Design?

我在我的一个限界上下文中使用域驱动设计,我使用Factory方法来创建我的域聚合和执行我的业务规则和不变量,但我的问题是有时我有很多属性的大型聚合,这些属性中的大多数只是数据属性,而不是不会影响聚合状态的行为属性,因此,使用它是一场噩梦工厂方法来填充所有这些属性,请告诉我如何使用最佳实践来做到这一点?

public async Task CreateEmployeeAsync(CreateOrUpdateEmployeeInput input)
    {
        Guard.ArgumentNotNull(input.Employee, nameof(input.Employee));
        var employeeDto = input.Employee;
        Address address = null;
        if (employeeDto.Address != null)
            address = new Address(employeeDto.Address.Street, employeeDto.Address.City, employeeDto.Address.State,
                employeeDto.Address.Country, employeeDto.Address.ZipCode);

        var employee = Employee.Create(employeeDto.FirstName, employeeDto.LastName, employeeDto.Email,
            employeeDto.DateOfJoining, employeeDto.DepartmentId, employeeDto.EmployeeType,
            employeeDto.ReportTo, employeeDto.Title, employeeDto.AllowSystemAccess, address);

        //These properties are just data properties, they will not affect the state of the aggregate
        //This is a nightmare to fill each one hand by hand or even using Factory
        employee.MobilePhone = input.Employee.MobilePhone;
        employee.WorkPhone = input.Employee.WorkPhone;
        employee.MaritalStatus = input.Employee.MaritalStatus;
        await _employeeRepository.InsertAsync(employee);
    }

移动phone和工作phone等"data properties"是聚合状态的一部分。并且有与它们相关的业务规则。例如:phone 号码必须有效。 MaritalStatus 可以是 3 个预定义值之一,不需要 WorkPhone ...

创建 Employee 对象时需要验证这些属性。 我可以建议的是将它们添加到构造函数中。 在这种情况下,您的域模型有很多属性,并且无法避免设置它们。我不推荐自动化的东西,因为它会以某种方式隐藏一些属性。下一个将使用此代码的开发人员将像:"I can't see where is the mobile phone being set ",这将增加处理该部分代码时的认知负荷。您将需要了解域模型和自动映射器或用于自动填充属性的工具,以便了解正在发生的事情。

属性多不一定是坏事。如果您想改进聚合设计,如果这对您的业务有意义,您可以将一些属性分组到一个新的值对象中。例如,您可以创建一个包含电子邮件和 phone 号码的 ContactInfo 值对象。