Can I detect if my code is executing in an Azure worker role?

For anyone interested, thought I would sharehow I implemented, thanks to @Sandrino Di Mattia's answer:

You can check for the presence of the RoleRoot environment variable (for Cloud Services at least):

Note that this does NOT cater for a Winforms App as I only actually required it in the end for Services - i.e. detecting between service running as

  • Azure Worker Role
  • Windows Service
  • Console Application

This is an outline:

public static class ServiceRunner
{
    private static bool IsAzureWorker
    { 
        get { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("RoleRoot")); } 
    }

    public static void Run(string[] args)
    {
        if (IsAzureWorker)
        {
            //Running as Azure Worker
        }
        else if (Environment.UserInteractive) //note, this is true for Azure emulator too
        {
            //Running as Console App
        }
        else
        {
            //Running as Windows Service
        }
    }
}

You can check for the presence of the RoleRoot environment variable (for Cloud Services at least):

  • MSDN

Or, why not simply add a setting to your config (AppSettings or Service Configuration):

  <appSettings>
    ...
    <add key="AppEnvironment" value="Azure.CloudService|Azure.Website" />
  </appSettings>

Then you can simply check if the setting exists with a specific value to see where you're running. This also means that during your (automated) build or deploy process you'll need to include this setting (this is possible with XDT for example).

Tags:

C#

Azure