-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSaga.cs
More file actions
87 lines (71 loc) · 2.49 KB
/
Saga.cs
File metadata and controls
87 lines (71 loc) · 2.49 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using Messages;
using NServiceBus;
using NServiceBus.Saga;
namespace Server
{
public class AbandonedCartSaga :
Saga<AbandonedCartSagaData>,
IAmStartedByMessages<ItemAddedToCart>,
IHandleMessages<OrderSubmitted>,
IHandleTimeouts<AbandonedCartTimeout>
{
public void Handle(ItemAddedToCart message)
{
Console.WriteLine("Received ItemAddedToCart for " + message.UserName);
Data.UserName = message.UserName;
Data.LastTimeoutId = Guid.NewGuid();
RequestTimeout(
TimeSpan.FromSeconds(5),
new AbandonedCartTimeout {
Id = Data.LastTimeoutId
}
);
}
public void Handle(OrderSubmitted message)
{
Console.WriteLine("Received OrderSubmitted for " + message.UserName);
// If the order is submitted, we can cancel this saga.
MarkAsComplete();
}
public void Timeout(AbandonedCartTimeout state)
{
if (Data.LastTimeoutId != state.Id) {
// This is not the last timeout issued, so ignore it.
return;
}
Console.WriteLine("Timeout reached for: " + Data.UserName);
Bus.SendLocal(new SendAbandonedCartEmail {
UserName = Data.UserName
});
MarkAsComplete();
}
protected override void ConfigureHowToFindSaga(SagaPropertyMapper<AbandonedCartSagaData> mapper)
{
mapper
.ConfigureMapping<ItemAddedToCart>(x => x.UserName)
.ToSaga(x => x.UserName);
mapper
.ConfigureMapping<OrderSubmitted>(x => x.UserName)
.ToSaga(x => x.UserName);
}
}
public class AbandonedCartTimeout
{
public Guid Id { get; set; }
}
public class AbandonedCartSagaData : IContainSagaData
{
// Built-in saga properties:
public Guid Id { get; set; }
public string Originator { get; set; }
public string OriginalMessageId { get; set; }
// Our properties, specific to this saga:
// This needs to be unique so that we can scale out, or
// we might get 2 Sagas with the same username,
// per https://twitter.com/UdiDahan/status/587896128688951297
[Unique]
public string UserName { get; set; }
public Guid LastTimeoutId{ get; set; }
}
}