Created
January 22, 2014 15:38
-
-
Save dlidstrom/8560915 to your computer and use it in GitHub Desktop.
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 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