Skip to content

Instantly share code, notes, and snippets.

@trbngr
Created June 28, 2011 18:10
Show Gist options
  • Save trbngr/1051764 to your computer and use it in GitHub Desktop.
Save trbngr/1051764 to your computer and use it in GitHub Desktop.
Injecting Message Information in Lokad CQRS v2
public static class ExtendImmutableEnvelope
{
public static Guid GetGuid(this ImmutableEnvelope envelope, string key)
{
return Get(envelope, key, s =>
{
Guid result;
return Guid.TryParse(s, out result) == false ? Guid.Empty : result;
});
}
public static int GetInt(this ImmutableEnvelope envelope, string key)
{
return Get(envelope, key, s =>
{
int result;
return int.TryParse(s, out result) == false ? 0 : result;
});
}
public static string GetString(this ImmutableEnvelope envelope, string key)
{
return Get(envelope, key, s => s);
}
private static T Get<T>(this ImmutableEnvelope envelope, string key, Func<string, T> convert)
{
ImmutableAttribute attribute =
envelope.GetAllAttributes().Where(a => a.Key == key).FirstOrDefault();
return convert(attribute == null ? string.Empty : attribute.Value);
}
}
public class MyCommandHandler : Define.Handle<MyCommand>
{
private readonly Func<MyCustomContext> contextFactory;
public MyCommandHandler(Func<MyCustomContext> contextFactory)
{
this.contextFactory = contextFactory;
}
#region Implementation of IConsume<in Command>
public void Consume(MyCommand message)
{
var context = contextFactory();
Console.Out.WriteLine(context.TenantId);
}
#endregion
}
[ProtoContract]
[DataContract]
public class MyCustomContext
{
[ProtoMember(1)]
[DataMember(Order = 1)]
public int TenantId { get; set; }
public static MyCustomContext Factory(ImmutableEnvelope envelope, ImmutableMessage message)
{
return new MyCustomContext
{
TenantId = envelope.GetInt("TenantId")
};
}
}
IMessageSender sender is injected;
sender.SendOne(new MyCommand(), b => b.AddString("TenantId", "123"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment