Chronicle is simple process manager/saga pattern implementation for .NET Core that helps you manage long-living and disitrbuted transactions.
master | develop | |
---|---|---|
AppVeyor | ||
CodeCov |
Chornicle is available on NuGet
Install-Package Chronicle_ -Version 1.8.0
dotnet add package Chronicle_ --version 1.8.0
In order to create and process saga you need to go through few steps:
- Create a class that dervies either from
Saga
orSaga<TData>
. - Inside saga implement particular steps that needs to be done or compensated in case of error. The initial step must be implemented as
ISagaStartAction<TMessage>
while the restISagaAction<TMessage>
. It's worth mentioning that up can implement as many start actions as you want. In this case first incomming message is going to initialize saga. - Register all your sagas in
Startup.cs
by callingservices.AddChronicle()
. - Inject
ISagaCoordinator
and inokeProcessAsync()
methods passing a message. Cooridnator will take care of everything by looking for all implemented sagas that can handle given message.
Bellow is the very simple example of saga that completes once both messages (Message1
and Message2
) are received:
public class Message1
{
public string Text { get; set; }
}
public class Message2
{
public string Text { get; set; }
}
public class SagaData
{
public bool IsMessage1Received { get; set; }
public bool IsMessage2Received { get; set; }
}
public class SampleSaga : Saga<SagaData>, ISagaStartAction<Message1>, ISagaAction<Message2>
{
public Task HandleAsync(Message1 message, ISagaContext context)
{
Data.IsMessage1Received = true;
Console.WriteLine($"Received message1 with message: {message.Text}");
CompleteSaga();
return Task.CompletedTask;
}
public Task HandleAsync(Message2 message, ISagaContext context)
{
Data.IsMessage2Received = true;
Console.WriteLine($"Received message2 with message: {message.Text}");
CompleteSaga();
return Task.CompletedTask;
}
public Task CompensateAsync(Message1 message, ISagaContext context)
=> Task.CompletedTask;
public Task CompensateAsync(Message2 message, ISagaContext context)
=> Task.CompletedTask;
private void CompleteSaga()
{
if(Data.IsMessage1Received && Data.IsMessage2Received)
{
Complete();
Console.WriteLine("SAGA COMPLETED");
}
}
}
Both messages are processed by mentioned coordinator:
var coordinator = app.ApplicationServices.GetService<ISagaCoordinator>();
var context = SagaContext
.Create()
.WithCorrelationId(Guid.NewGuid())
.Build();
coordinator.ProcessAsync(new Message1 { Text = "Hello" }, context);
coordinator.ProcessAsync(new Message2 { Text = "World" }, context);
The result looks as follows:
If you're looking for documentation, you can find it here.
Icon made by Smashicons from www.flaticon.com is licensed by Creative Commons BY 3.0