Skip to content

Instantly share code, notes, and snippets.

@dlidstrom
Created January 22, 2014 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlidstrom/8560915 to your computer and use it in GitHub Desktop.
Save dlidstrom/8560915 to your computer and use it in GitHub Desktop.
public class BackgroundTasksQueueProcessor : MessageQueueProcessorBase
{
private static readonly JsonSerializerSettings SerializerSettings
= new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
private readonly IKernel kernel;
public BackgroundTasksQueueProcessor(
IKernel kernel,
string importQueue,
string errorQueue,
int count)
: base(kernel, importQueue, errorQueue, count)
{
this.kernel = kernel;
}
protected override void DoHandle(string contents)
{
if (contents == null) throw new ArgumentNullException("contents");
var task = JsonConvert.DeserializeObject(contents, SerializerSettings);
var handlerType = typeof(ITaskHandler<>).MakeGenericType(task.GetType());
object handler = null;
ICommandExecutor commandExecutor = null;
try
{
handler = kernel.Resolve(handlerType);
commandExecutor = kernel.Resolve<ICommandExecutor>();
// invoke the Handle method
var handleMethod = handlerType.GetMethod("Handle");
handleMethod.Invoke(handler, new[] { task });
commandExecutor.SaveChanges();
}
catch (ComponentNotFoundException ex)
{
var message =
string.Format(
"No handler found for {0}. Implement IBackgroundTask<{0}>",
task.GetType().Name);
throw new ApplicationException(message, ex);
}
finally
{
if (handler != null) kernel.ReleaseComponent(handler);
if (commandExecutor != null) kernel.ReleaseComponent(commandExecutor);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment