Consider a class that has some events. This event list is going to grow. Some are optional. Others are required.
To simplify some initial validation I have a custom attribute that marks an event as a required one. For example:
[RequiredEventSubscription("This event is required!")]
public event EventHandler ServiceStarted;
So far so good. To validate all events, using reflection I iterate the event list and grab the custom attributes. But I need a way to determine if the event is subscribed or not.
Without reflection the ServiceStarted.GetInvocationList does the job. But the event must come from this list: var eventList = this.GetType().GetEvents().ToList();
Is there any way to check if a given event, from an event list, is subscribed using reflection?
--[Update]-- Here's a possible solution based on Ami's answer:
private void CheckIfRequiredEventsAreSubscribed()
{
var eventList = GetType().GetEvents().ToList().Where(e => Attribute.IsDefined(e, typeof(RequiredEventSubscription)));
StringBuilder exceptionMessage = new StringBuilder();
StringBuilder warnMessage = new StringBuilder();
foreach (var evt in eventList)
{
RequiredEventSubscription reqAttr = (RequiredEventSubscription) evt.GetCustomAttributes(typeof(RequiredEventSubscription), true).First();
var evtDelegate = this.GetType().GetField(evt.Name, BindingFlags.Instance | BindingFlags.NonPublic);
if (evtDelegate.GetValue(this) == null)
{
warnMessage.AppendLine(reqAttr.warnMess);
if (reqAttr.throwException) exceptionMessage.AppendLine(reqAttr.warnMess);
}
}
if (warnMessage.Length > 0)
Console.WriteLine(warnMessage);
if (exceptionMessage.Length > 0)
throw new RequiredEventSubscriptionException(exceptionMessage.ToString());
}
Many thanks!!