How to combine a Worker Role and an MVC4 Web Role into a single Azure instance

December 22nd, 2011

I wanted to expand on a great blog post that Wayne Berry did on the subject of combining web and worker roles into a single machine instance.  As Wayne mentioned, this is a great way to help save money when you do not need a high end machine for your web application and worker processes and it is more efficient to combine these into a single machine instance.  By default, you get allocated one instance for the worker role and another machine for your web site.  If you want an SLA, you would need 2 of each.  Certainly for a new business looking to keep the costs low it would be far better if you could combine these roles into a single machine.

The interesting thing is that a Windows Azure web role is actually just a worker role with some IIS capabilities. The trick to combine these is to make a web role add a subclass called RoleEntryPoint which is what is used by the worker role.  For MVC2, this is really easy and Wayne’s blog explains this really well.  Unfortunately, for my MVC4 Web role, there was no Webrole.cs file.  No problem, this can easily be fixed by adding a new class.  To do this, right click on the MVC4 project and choose Add | Class.

add c# class

I called mine WebWorker.cs

After that you simple add code that would look similar to the following and you are done.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.StorageClient;
using System.Diagnostics;
using System.Threading;

namespace MyMVC4ProjectUI
{
public class WebWorker : Microsoft.WindowsAzure.ServiceRuntime.RoleEntryPoint
{
public override bool OnStart()
{

return base.OnStart();
}

public override void Run()
{
// This is a sample worker implementation. Replace with your logic.
Trace.WriteLine("WorkerRole1 entry point called", "Information");

while (true)
{
Thread.Sleep(10000);
Trace.WriteLine("Working", "Information");
}
}
}
}

Leave a Reply