Created
July 12, 2019 07:27
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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