Skip to content

Instantly share code, notes, and snippets.

@sheastrickland
Created June 12, 2014 10:44
Show Gist options
  • Save sheastrickland/d3c63591567bb33f94fa to your computer and use it in GitHub Desktop.
Save sheastrickland/d3c63591567bb33f94fa to your computer and use it in GitHub Desktop.
CorrelationContext - For help correlating messages between processes and consumers
using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Messaging;
namespace Nimble.Messaging
{
public static class CorrelationContext
{
public const string RequestIdKey = "Correlation.RequestId";
public const string MessageIdKey = "Correlation.MessageId";
public static string MessageId
{
get { return MessageIdKey.Get<string>(); }
set { MessageIdKey.Set(value); }
}
public static string RequestId
{
get { return RequestIdKey.Get(() => Guid.NewGuid().ToString()); }
set { RequestIdKey.Set(value); }
}
static T Get<T>(this string key, Func<T> defaulter = null)
{
var value = (T)CallContext.LogicalGetData(key);
if (EqualityComparer<T>.Default.Equals(value, default(T)) && defaulter != null)
{
value = defaulter();
key.Set(value);
}
return value;
}
static void Set<T>(this string key, T value)
{
CallContext.LogicalSetData(key, value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment