-
Notifications
You must be signed in to change notification settings - Fork 76
/
Infrastructure.cs
55 lines (45 loc) · 1.44 KB
/
Infrastructure.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleankka;
using Orleankka.Meta;
namespace Example
{
public abstract class EventSourcedActor : DispatchActorGrain
{
StreamRef<IEventEnvelope> stream;
public override Task<object> Receive(object message)
{
switch (message)
{
case Activate _:
stream = System.StreamOf<IEventEnvelope>("sms", $"{GetType().Name}-{Id}");
return Result(Done);
case Command cmd:
return HandleCommand(cmd);
default:
return base.Receive(message);
}
}
async Task<object> HandleCommand(Command cmd)
{
var events = Dispatcher.DispatchResult<IEnumerable<Event>>(this, cmd);
foreach (var @event in events)
{
Dispatcher.Dispatch(this, @event);
await Project(@event);
}
return events;
}
Task Project(Event @event)
{
var envelope = Wrap(@event);
return stream.Publish(envelope);
}
IEventEnvelope Wrap(Event @event)
{
var envelopeType = typeof(EventEnvelope<>).MakeGenericType(@event.GetType());
return (IEventEnvelope) Activator.CreateInstance(envelopeType, Id, @event);
}
}
}