Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Created July 12, 2019 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramonsmits/552bc032336174ebb1054ec6896e38f6 to your computer and use it in GitHub Desktop.
Save ramonsmits/552bc032336174ebb1054ec6896e38f6 to your computer and use it in GitHub Desktop.
NServiceBus - Map a header value to a message property to be used in a saga
using System;
using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.Pipeline;
class Program
{
static async Task Main(string[] args)
{
var cfg = new EndpointConfiguration("test");
cfg.UseTransport<LearningTransport>();
cfg.Pipeline.Register(new MapHeaderToPropertyBehavior(), "mapper");
var instance = await Endpoint.Start(cfg);
do
{
await instance.SendLocal(new MyMessage());
} while (Console.ReadKey().Key != ConsoleKey.Escape);
await instance.Stop();
}
}
interface IConversation
{
string ConversationId { get; set; }
}
class MyMessage : IConversation, IMessage
{
public string ConversationId { get; set; }
}
class MapHeaderToPropertyBehavior : Behavior<IIncomingLogicalMessageContext>
{
public override Task Invoke(IIncomingLogicalMessageContext context, Func<Task> next)
{
var msg = context.Message.Instance as IConversation;
if (msg != null && context.Headers.TryGetValue(Headers.ConversationId, out var headerValue))
{
msg.ConversationId = headerValue;
}
return next();
}
}
class MyHandler : IHandleMessages<MyMessage>
{
public Task Handle(MyMessage message, IMessageHandlerContext context)
{
return Console.Out.WriteLineAsync(">" + message.ConversationId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment