Over a million developers have joined DZone.

How to determine event subscriptions at runtime

·

I’ve been wanting to know this for years, and finally discovered it the other day when looking inside the Microsoft Composite Application Blocks class in Microsoft.Practices.CompositeUI.BuilderStrategies.CommandStrategy.

There’s some code in this class to discover if an event handler has already been attached to the event, and it goes a little something like this…

private void RegisterCommandHandlers(IBuilderContext context, WorkItem workItem, object target,
string targetID, MethodInfo methodInfo)
{
foreach (CommandHandlerAttribute attr in methodInfo.GetCustomAttributes(typeof(CommandHandlerAttribute), true))
{
Command cmd = workItem.Commands[attr.CommandName];

if (!cmd.IsHandlerRegistered(target, methodInfo))
{
cmd.ExecuteAction += CreateCommandHandler(target, methodInfo);
TraceBuildUp(context, target.GetType(), targetID, Properties.Resources.CommandInjectionBuildUp,
methodInfo.Name, attr.CommandName);
}
}
}

The clever part is the IsHandlerRegistered method above, which uses the System.MulticastDelegate.GetInvocationList() method to discover all the targets of the event…

internal bool IsHandlerRegistered(object target, MethodInfo methodInfo)
{
if (ExecuteAction != null)
{
foreach (Delegate dlg in ExecuteAction.GetInvocationList())
{
if (dlg.Target == target && dlg.Method == methodInfo)
{
return true;
}
}
}
return false;
}
Topics:

Published at DZone with permission of Merrick Chaffer, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}