看一个聚合根:
public class ExampleAggregate : AggregateRoot<ExampleAggregate, ExampleId>, IEmit<ExampleEvent> { private int? _magicNumber; private int NameExample; public ExampleAggregate(ExampleId id) : base(id) { } // Method invoked by our command public IExecutionResult SetMagicNumer(int magicNumber,int n) { if (_magicNumber.HasValue) return ExecutionResult.Failed("Magic number already set"); Emit(new ExampleEvent(magicNumber, n)); return ExecutionResult.Success(); } // We apply the event as part of the event sourcing system. EventFlow // provides several different methods for doing this, e.g. state objects, // the Apply method is merely the simplest public void Apply(ExampleEvent aggregateEvent) { _magicNumber = aggregateEvent.MagicNumber; NameExample = aggregateEvent.NameExample; } }
实现了IEmit 接口,那么
Emit(new ExampleEvent(magicNumber, n));
这句话执行的时候,
就会触发领域事件的执行。
这个Emit 是AggregateRoot 的方法。在AggregateRoot 的Emit 方法中,调用apply 方法。
下面是ReadModel ,实现了 IAmReadModelFor<ExampleAggregate, ExampleId, ExampleEvent> 接口
public class ExampleReadModel : IReadModel, IAmReadModelFor<ExampleAggregate, ExampleId, ExampleEvent> { public int MagicNumber { get; private set; } public int NameExample { get; private set; } public void Apply(IReadModelContext context, IDomainEvent<ExampleAggregate, ExampleId, ExampleEvent> domainEvent) { MagicNumber = domainEvent.AggregateEvent.MagicNumber; NameExample = domainEvent.AggregateEvent.NameExample; } }