Skip to content

8. Azure Queue Dispatch and Execution

James Randall edited this page Dec 3, 2017 · 1 revision

Applies to v5.0.0 and higher. See revision history for documentation for prior versions.

A sample is available that illustrates this however I'll also cover the important points below. I'm going to assume a couple of things in the below:

  1. You have a queue of type CloudQueue called myQueue: CloudQueue myQueue = .... queue from CloudQueueClient ....;
  2. That your dispatch and reciept are in different systems (for example a REST API dispatches the command and a Web Job processes it)

To get started you'll need to install a couple of NuGet packages in both the dispatch and process halves (so in our example in the REST API and the Web Job):

Install-Package AzureFromTheTrenches.Commanding.Queue
Install-Package AzureFromTheTrenches.Commanding.AzureStorage

And then install the queue based commanding system:

resolver.UseQueues().UseAzureStorageCommanding();

On the dispatch side registering (our REST API) a command is a little more complicated with a queue as you need to supply the Azure Storage Queue dispatcher as a custom dispatcher:

ICommandDispatcher QueueDispatcher() => resolver.Resolve<IAzureStorageQueueDispatcherFactory>().Create(queue);
registry.Register<AddCommand>(QueueDispatcher);

You'll note in the above I don't specify a result type. Queue dispatch is currently one way only. Dispatching a command is the same as ever:

await commandDispatcher.DispatchAsync(new AddCommand { FirstNumber = 5, SecondNumber = 6});

On the queue processing side (our Web Job) again you need to install the queue based commanding system and register our command with it's actor.

ICommandRegistry registry = resolver.UseCommanding(type => resolver.Register(type, type));
resolver.UseQueues().UseAzureStorageCommanding();
registry.Register<AddCommand, AddCommandActor>();

Although you could write code to pull items from the queue and execute them much as we did with HTTP Helper systems are provided that will watch a queue (with a backoff algorithm) and dispatch the items that appear for execution. You configure them as below:

IAzureStorageCommandQueueProcessorFactory listenerFactory = resolver.Resolve<IAzureStorageCommandQueueProcessorFactory>();
Task longRunningTask = listenerFactory.Start<AddCommand, AddCommand>(queue, cancellationTokenSource.Token);

You need to manage the task execution and make sure your Web Job doesn't quit but that's a pretty standard pattern for a Web Job that I won't cover here.

(Note: Service bus equivalants will be available as soon as the Microsoft Service Bus package for .NET Standard exits preview)