Created
March 24, 2014 19:58
-
-
Save jyoung/9747805 to your computer and use it in GitHub Desktop.
EasyNetQ StuctureMapDispatcher
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
public class FakeAsyncMessageConsumer : IConsumeAsync<FakeMessage> | |
{ | |
public Task Consume(FakeMessage message) | |
{ | |
return Task.Factory.StartNew(() => | |
{ | |
Console.Out.WriteLine("Hello World Async!"); | |
}); | |
} | |
} |
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
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