Skip to content

Instantly share code, notes, and snippets.

@jyoung
Created March 24, 2014 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jyoung/9747805 to your computer and use it in GitHub Desktop.
Save jyoung/9747805 to your computer and use it in GitHub Desktop.
EasyNetQ StuctureMapDispatcher
public class FakeAsyncMessageConsumer : IConsumeAsync<FakeMessage>
{
public Task Consume(FakeMessage message)
{
return Task.Factory.StartNew(() =>
{
Console.Out.WriteLine("Hello World Async!");
});
}
}
public class StructureMapMessageDispatcher : IAutoSubscriberMessageDispatcher
{
private static readonly ILog log = LogManager.GetLogger(typeof (StructureMapMessageDispatcher));
private readonly IContainer container;
public StructureMapMessageDispatcher(IContainer container)
{
this.container = container;
}
public Action<IContainer> BeforeDispatch { get; set; }
public Action<IContainer, Exception> AfterDispatch { get; set; }
public void Dispatch<TMessage, TConsumer>(TMessage message) where TMessage : class where TConsumer : IConsume<TMessage>
{
using (var nested = container.GetNestedContainer())
{
try
{
var consumer = nested.GetInstance<TConsumer>();
if (BeforeDispatch != null)
{
BeforeDispatch(nested);
}
consumer.Consume(message);
if (AfterDispatch != null)
{
AfterDispatch(nested, null);
}
}
catch (Exception ex)
{
if (AfterDispatch != null)
{
AfterDispatch(nested, ex);
}
// TODO: Handle the error
// will need to handle the error here if I cannot get access to the queue name in the error strategy
throw;
}
}
}
public Task DispatchAsync<TMessage, TConsumer>(TMessage message) where TMessage : class where TConsumer : IConsumeAsync<TMessage>
{
return Task.Factory.StartNew(() =>
{
using (var nested = container.GetNestedContainer())
{
try
{
if (BeforeDispatch != null)
{
BeforeDispatch(nested);
}
var consumer = nested.GetInstance<TConsumer>();
// wait for the consumer to finish?
consumer.Consume(message).Wait();
if (AfterDispatch != null)
{
AfterDispatch(nested, null);
}
}
catch (Exception ex)
{
if (AfterDispatch != null)
{
AfterDispatch(nested, ex);
}
// TODO: Handle the error
// will need to handle the error here if I cannot get access to the queue name in the error strategy
throw;
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment