假设我们有一个任务记录系统,当记录一个任务时,用户指定一个类别,并且该任务默认为“未完成”状态。在这种情况下,假定类别和状态必须作为实体实施。通常我会这样做:
应用层:
public class TaskService
{
    //...
    public void Add(Guid categoryId, string description)
    {
        var category = _categoryRepository.GetById(categoryId);
        var status = _statusRepository.GetById(Constants.Status.OutstandingId);
        var task = Task.Create(category, status, description);
        _taskRepository.Save(task);
    }
}
实体:
public class Task
{
    //...
    public static void Create(Category category, Status status, string description)
    {
        return new Task
        {
            Category = category,
            Status = status,
            Description = descrtiption
        };
    }
}
我这样做是因为我一直被告知实体不应该访问存储库,但是如果这样做的话,对我来说更有意义:
实体:
public class Task
{
    //...
    public static void Create(Category category, string description)
    {
        return new Task
        {
            Category = category,
            Status = _statusRepository.GetById(Constants.Status.OutstandingId),
            Description = descrtiption
        };
    }
}
无论如何,状态存储库都是依赖注入的,因此没有真正的依赖关系,在我看来,是由域决定任务默认为未完成。以前的版本感觉像是由应用程序层做出该决定。为什么这不是一个可能的原因,为什么存储合同通常在域中?
这是一个更极端的示例,在此域决定紧急程度:
实体:
public class Task
{
    //...
    public static void Create(Category category, string description)
    {
        var task = new Task
        {
            Category = category,
            Status = _statusRepository.GetById(Constants.Status.OutstandingId),
            Description = descrtiption
        };
        if(someCondition)
        {
            if(someValue > anotherValue)
            {
                task.Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.UrgentId);
            }
            else
            {
                task.Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.SemiUrgentId);
            }
        }
        else
        {
            task.Urgency = _urgencyRepository.GetById
                (Constants.Urgency.NotId);
        }
        return task;
    }
}
您没有办法传递所有可能的Urgency版本,也没有办法在应用程序层中计算此业务逻辑,因此,这肯定是最合适的方法吗?
那么这是从域访问存储库的有效理由吗?
编辑:非静态方法也可能是这种情况:
public class Task
{
    //...
    public void Update(Category category, string description)
    {
        Category = category,
        Status = _statusRepository.GetById(Constants.Status.OutstandingId),
        Description = descrtiption
        if(someCondition)
        {
            if(someValue > anotherValue)
            {
                Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.UrgentId);
            }
            else
            {
                Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.SemiUrgentId);
            }
        }
        else
        {
            Urgency = _urgencyRepository.GetById
                (Constants.Urgency.NotId);
        }
        return task;
    }
}