Search code examples
c#azureazure-web-roles

How to unsubscribe from subscription when webrole is deleting by autoscaling?


I use Ninject for my app.

public class Global : NinjectHttpApplication

On Application started I call:

protected override void OnApplicationStarted()
...
            if (RoleEnvironment.IsAvailable)
            {
                RoleEnvironment.Stopping += (sender, args) =>
                {
                    messagesListener.Stop(true);
                    Logger.LogInfo("Website is stopping. InstanceNo = " + instanceNo);
                };
        }

But for some reason this event Stopping is not called. Please help me. I hear that probably I need to use OnStop event from RoleEntryPoint class which I can inherit in my class, but I am not sure how to do it. I read this article: What's the difference between the webrole onStart() event and Application_Start() global.asax event?


Solution

  • There should be a class in your web project called WebRole.cs. This class is added by default to all web-based Azure projects that are based on Cloud Services.

    If you dont see that class in your project, you can simply add it. In it, is where you configure event handler for Stopping event

    public class WebRole : RoleEntryPoint
    {
        public override bool OnStart()
        {
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
    
            RoleEnvironment.Stopping += (sender, args) =>
                {
                    messagesListener.Stop(true);
                    Logger.LogInfo("Website is stopping. InstanceNo = " + instanceNo);
                };
    
            return base.OnStart();
        }
    
        public override void OnStop()
        {
            // you can also put stuff here to test
            base.OnStop();
        }
    }