Implement custom EventHub events

Although Sitefinity CMS provides many events raised by the built-in modules, you can also create your custom events providing hooks to your code. In order to implement a custom event, you need to follow 3 steps.

Create the interface and its implementation

All events provide an interface specifying the contract for the event. The interface has all properties that will be passed to the event handler as data. You should implement a custom interface for your event and include any properties you want. All interfaces should implement the IEventinterface.

When you raise the event, you will need to create an instance which will be passed to the handler. Since you cannot create interface instances, you will need a class which implements the interface.

C#
using System;
using Telerik.Sitefinity.Services.Events;

namespace SitefinityWebApp
{
   public interface ICustomEvent : IEvent
   {
       int MyCustomInteger { get; set; }
       string MyCustomMessage { get; set; }
   }

   public class CustomEvents : ICustomEvent
   {
       public string Origin { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

       public int MyCustomInteger { get; set; }
       public string MyCustomMessage { get; set; }
   }
}

Raising the event

Whenever you want to invoke the event handlers which have subscribed to your event, you should raise it. This can be done using a helper method of the EventHubclass.

C#
using Telerik.Sitefinity.Services;

namespace SitefinityWebApp
{
   public class RiseEvent
   {
       public void RiseEventMethod()
       {
           EventHub.Raise(new CustomEvents
           {
               MyCustomInteger = 2,
               MyCustomMessage = "Hey there. Here's some event info."
           });
       }
   }
}

After you've done this, everyone will be able to subscribe to your event using the ICustomEventinterface. For more information on subscribing, read For developers: Work with events.

Want to learn more?
Enhance your Sitefinity skills by enrolling in free training sessions. Become Sitefinity certified through Progress Education Community to strengthen your professional credentials.