Help! My EventHub events are running multiple times

The EventHub is a great system for subscribing to events in Sitefinity. For instance, if you want to run some code whenever a user logs in, you can subscribe to the ILoginCompletedEvent for this. You can check out the full list of available events here.

The issue

Anyways, I often see users of the EventHub run into a common issue. They will complain to me that when they use EventHub, they are seeing their subscribed method run twice or multiple times.

The cause

More often than not, this is due to not subscribing correctly. For instance:

    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            Bootstrapper.Initialized += new EventHandler<ExecutedEventArgs>(this.Bootstrapper_Initialized);
        }

        private void Bootstrapper_Initialized(object sender, ExecutedEventArgs e)
        {
            EventHub.Subscribe<ILoginCompletedEvent>(LoginCompletedEventVerification);
        }

        private void LoginCompletedEventVerification(ILoginCompletedEvent evt)
        {
            // Run my code
        }
    }

The code above will likely cause your login method to run two times when a user logs in. This is because you are subscribing in the Bootstrapper_Initialized method. It is common to run some startup code here, but this method fires more than once (different e.CommandName each time).

The fix

    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            SystemManager.ApplicationStart += SystemManager_ApplicationStart;
        }

        private void SystemManager_ApplicationStart(object sender, EventArgs e)
        {
            EventHub.Subscribe<ILoginCompletedEvent>(LoginCompletedEventVerification);
        }

        private void LoginCompletedEventVerification(ILoginCompletedEvent evt)
        {
            // Run my code
        }
    }

Using the SystemManager.ApplicationStart event is the safer way to subscribe to events. If you want to take a step further and be extra safe, you could also unsubscribe from events in the SystemManager.Shutdown event.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *