0

Is there a way to capture the RoleEnvironment.CurrentRoleInstance.Role.Name on UnityWebApiActivator.Start and UnityWebApiActivator.Shutdown or another equivalent method?

Edit 1:
The current code always returns "localhost" (even after deploying to azure)

var name = RoleEnvironment.IsAvailable ? RoleEnvironment.CurrentRoleInstance.Role.Name : "localhost";
Leonardo
  • 10,737
  • 10
  • 62
  • 155

1 Answers1

1

According to this thread. What starts first Application_Start or WebRole's OnStart?

Prior to 1.3, the Hosted Worker Core (HWC) was hosted in the RoleEntryPoint, so there was a deterministic startup (OnStart, Application_OnStart, IIRC). However, with IIS hosting the web now, it is the IISConfigurator.exe that creates the app pool, etc, and eventually w3wp.exe hosts your web site. This is a different process than your RoleEntryPoint, so either one could start first.

As we know, UnityWebApiActivator.Start method is executed before Application_OnStart. So we can't determine which method will be executed for UnityWebApiActivator.Start and RoleEntryPoint.OnStart. So the IsAvailable property of RoleEnvironment will be false if UnityWebApiActivator.Start method executes first.

If you want to get the role name, I suggest you create a custom RoleEntryPoint and get the role name in its OnStart method.

public class MyRoleEntryPoint: RoleEntryPoint
{
    public override bool OnStart()
    {
        var name = RoleEnvironment.IsAvailable ? RoleEnvironment.CurrentRoleInstance.Role.Name : "localhost";
        return base.OnStart();
    }
}

Another workaround is wait until the RoleEnvironment is available before getting the role name.

public class UnityWebApiActivator
{
    public static void Start()
    {
        while (!RoleEnvironment.IsAvailable)
        {
            Thread.Sleep(100);
        }
        var name =  RoleEnvironment.CurrentRoleInstance.Role.Name;
    }
}
Amor
  • 8,325
  • 2
  • 19
  • 21