Welcome to EMC Consulting Blogs Sign in | Join | Help

Merrick Chaffer's Blog

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;
        }
Published 02 February 2011 09:58 by merrick.chaffer

Comments

No Comments
Anonymous comments are disabled

This Blog

Syndication

News

Powered by Community Server (Personal Edition), by Telligent Systems