1

Within my application service, I have the following code for publishing domain events:

var document = await dbContext.Documents.GetAggregateAsync(message.DocumentId);

publisher.SubscribeTo<DocumentOwnerChanged>()
    .UsingDelegate(
        async a => await messageGateway.DocumentOwnerChanged(1, 1, 1));

document.ChangeOwner(message.OwnerId);

await dbContext.SaveChangesAsync();

await publisher.Publish(document.ReleaseEvents());

I'm trying to decide if I like having this knowledge of publishing events within the app service or if I should externalize this somewhere up higher in the root.

thoughts?

Marco
  • 2,453
  • 3
  • 25
  • 35

1 Answers1

3

You would typically register handlers in the Composition Root, unless you had to dynamically register and un-register handlers based on other messages.

There is some discussion around this here

You would publish domain events typically in your domain layer:

public void SomeDomainBehaviour()
{
    // do something domain-y
    DomainEvents.Publish(new DomainEvent());
}

Jimmy Bogard discusses other ways of publishing Domain Events here

Community
  • 1
  • 1
tomliversidge
  • 2,339
  • 1
  • 15
  • 15
  • thank you i do prefer returning/storing events as opposed to the static publisher. – Marco Jul 29 '16 at 00:24
  • Jimmy's article is great. I've adopted a pattern based off of his, in that article. My only personal quibble with it is that it allows for multiple aggregates to participate in a single transaction. I've started opting more towards eventual consistency, which Jimmy's article still applies to if you put the base.Save() call at the beginning of the override and then dispatch your events. That is, IMO, a much better solution than an asynchronous dispatch. The handlers can execute asynchronously, but I would like to know if an event could not be published, personally. – Joseph Ferris Aug 06 '16 at 01:28