Can an aggregates invariant include a rule based on information from elsewhere?

后端 未结 2 1058
南笙
南笙 2021-02-20 14:08

In DDD can an aggregates invariant include a rule based on information in a another aggregate? Now I don\'t think so, however this causes me a problem and I don\'t know how to

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 14:39

    In this scenario, there are several methods for enforcing invariants.

    First of all, consider the behaviors around the Asset aggregate. I assume there is at least a CreateAssetCommand and a RemoveTagCommand. The invariants should be enforced during execution of these commands in the following way:

    CreateAssetCommand

    Since an asset is always associated with an asset type, an AssetTypeId must be provided as part of this command. This ID must be obtained by the caller, possibly by looking up a specific asset type. When AssetType is looked up, the corresponding TagType entities can also be retrieved, the mandatory ones in particular. This will allow the caller to construct the required Tag instances to send as part of the command. Note, it is the responsibility of the caller to provide a valid asset type and tags.

    RemoveTagCommand

    The handler for this command can retrieve the appropriate Asset which stores the AssetTypeId. Next, the handler retrieves the set of mandatory tags for the asset type and ensures that those tags aren't removed. In this case, the invariant is enforced by the handler itself.

    Another way to handle these invariants is to introduce eventual consistency, if acceptable. With this approach, removal of a tag from an asset should publish a TagRemovedEvent. A handler for this event can then verify that a mandatory tag wasn't removed. If it was, it can create a task or notification stating that an Asset is in an invalid state. Note, this assumes that it is acceptable for an asset to be in an invalid state until something is corrected.

    Now to behaviors around AssetType. One command that could compromise the integrity of the Asset aggregate is the introduction of a new mandatory Tag. In this case, the onyl way to ensure integrity is to create appropriate tags for each corresponding asset. Since this likely can't be done automatically, eventual consistency must be accepted until appropriate tags are provided via manual intervention.

    With all these approaches, you don't have the kind of integrity you'd get with a RDMS. The responsibility of enforcing cross-aggregate invariants is delegated to command handlers, event handlers and calling code. However, in many instances, this kind of consistency is perfectly acceptable.

    Take a look at Effective Aggregate Design for more on this.

提交回复
热议问题