Skip to content

Instantly share code, notes, and snippets.

@DavidBoike
Created March 29, 2018 18:35
Show Gist options
  • Save DavidBoike/8ab5b6c877bf1ca54eb9e307d517b355 to your computer and use it in GitHub Desktop.
Save DavidBoike/8ab5b6c877bf1ca54eb9e307d517b355 to your computer and use it in GitHub Desktop.
Example showing event handled by multiple sagas at the same time
using System;
using System.Data.SqlClient;
using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.Persistence.Sql;
namespace MultiSqlSagas
{
class Program
{
static async Task Main(string[] args)
{
var cfg = new EndpointConfiguration("MultiSqlSagas");
cfg.UseTransport<LearningTransport>();
cfg.EnableInstallers();
var p = cfg.UsePersistence<SqlPersistence>();
p.SqlDialect<SqlDialect.MsSqlServer>();
p.ConnectionBuilder(() => new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=NativeSql;Integrated Security=True;MultipleActiveResultSets=True"));
var ep = await Endpoint.Start(cfg);
while (true)
{
Console.WriteLine("Enter OrderId and press Enter to publish message.");
string orderId = Console.ReadLine();
await ep.Publish(new TheEvent { OrderId = orderId });
}
}
}
public class TheEvent : IEvent
{
public string OrderId { get; set; }
}
public class T1 { }
public class T2 { }
public class S1 : SqlSaga<S1.Data>, IAmStartedByMessages<TheEvent>, IHandleTimeouts<T1>
{
protected override string CorrelationPropertyName => "OrderId";
public Task Handle(TheEvent message, IMessageHandlerContext context)
{
Console.WriteLine("S1 handle");
return RequestTimeout<T1>(context, TimeSpan.FromSeconds(5));
}
protected override void ConfigureMapping(IMessagePropertyMapper mapper)
{
mapper.ConfigureMapping<TheEvent>(m => m.OrderId);
}
public class Data : ContainSagaData
{
public string OrderId { get; set; }
}
public Task Timeout(T1 state, IMessageHandlerContext context)
{
Console.WriteLine("Timeout1");
return Task.CompletedTask;
}
}
public class S2 : SqlSaga<S2.Data>, IAmStartedByMessages<TheEvent>, IHandleTimeouts<T2>
{
protected override string CorrelationPropertyName => "OrderId";
public Task Handle(TheEvent message, IMessageHandlerContext context)
{
Console.WriteLine("S2 handle");
return RequestTimeout<T2>(context, TimeSpan.FromSeconds(5));
}
protected override void ConfigureMapping(IMessagePropertyMapper mapper)
{
mapper.ConfigureMapping<TheEvent>(m => m.OrderId);
}
public class Data : ContainSagaData
{
public string OrderId { get; set; }
}
public Task Timeout(T2 state, IMessageHandlerContext context)
{
Console.WriteLine("Timeout2");
return Task.CompletedTask;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment