Click here to Skip to main content
13,347,998 members (65,466 online)
Click here to Skip to main content
Add your own
alternative version


37 bookmarked
Posted 6 Dec 2006

Loosely Coupled Event Driven Programming

, 6 Dec 2006
Rate this:
Please Sign up or sign in to vote.
This article shows how to assign events dynamically, the main target is to make the application very loosely coupled.

Sample Image


This article shows how to assign events dynamically, the target is to make the application very loosely coupled.

The code gives a brief idea on how to develop the application using Reflection, and how to dynamically associate methods to events.

Let me give a brief idea about the approach I followed. I have created two attributes and assigned the value of the attributes to be same for the event and the corresponding method. Dynamically, I am checking an event and trying to associate that event with the background method having the same attribute value. I will explain the step by step approach that I took. The first thing is we have to create two attributes (one for events and another for the methods).

public class EventAtrributePublisher : Attribute
    private string _name;
    public EventAtrributePublisher(string name)
        this._name = name;
    public string Name
            return this._name;

Same way, we have to create attributes for the publisher and make the attribute target as methods. Then, create custom event args, which we will be using while creating the event handler.

public class ParameterEventArgs:EventAr{

Create any collection object inside the above method, which will maintain the data and which can be passed to the methods. Assign the created attributes to the events/methods:

 public  event EventHandler<ParameterEventArgs> DynamicEvent;
 public void MethodEventHandler(object sender, 
             ParameterEventArgs pe)
    //Handle the method

The next core thing is linking the event with the method. For that, I created a manager where we have two static collection objects (one for methods and another for events). First load the method handler library dynamically, by specifying the path of the assembly.


This assembly has all the methods which get invoked while the associated event is raised. This assembly name can be configured in the application configuration file.

I have two static methods: AddSubscriber, PublishEvents, for adding method related stuff and event related stuff to the collection, respectively.

PublishEvents(object instance)
    Type t = instance.GetType();
    EventInfo[] events = t.GetEvents();
    foreach (EventInfo e in events)
        //Get only the events which are attributed 
        //with custom attribute "EventAtrributePublisher"
        EventAtrributePublisher attr = 
           typeof(EventAtrributePublisher), false);
        if (attr != null)
            //This following method adds the related 
            //information to the collection object.
            AddEventPublishEvent(attr.Name, instance, e);

In the above code, instance is nothing but the main form of the application (i.e., this). Next, add the method related stuff to the collection that is there in a given assembly.

public static void AddSubscriber(Assembly assembly)
    //We are interested in only the types 
    //which are visible from outside.
    Type[] allTypes = assembly.GetExportedTypes();
    if (allTypes != null)
        foreach (Type t in allTypes)
            if (t.IsClass)
                MethodInfo[] mtCollection = t.GetMethods();
                foreach (MethodInfo m in mtCollection)
                    //Get only the methods which are attributed 
                    //with "EventAttributeSubscriber"
                    EventAttributeSubscriber spa = 
                    if (spa != null)
                        //Add method related stuff to the collection object.
                        AddEventSubscriber(spa.Name, t, m);

Next comes the linking of events to the methods. I have one more static method which links the publisher to the subscriber. For that, it makes use of the attribute value. Here, I am dynamically creating the delegate and adding that particular event handler to the published event.

dlg = (Delegate)Activator.CreateInstance(pubEvent.EventHandlerType, 
       new object[] { instance, 
       mi.MethodHandle.GetFunctionPointer() });
//Can be done using Delegate.CreateDelegate also.
if (dlg != null)
    pubEvent.AddEventHandler(pubInstance, dlg);

The last step you have to take care of is, creating the custom event args object and invoking the required event.

if (CustomEvent != null)
    Hashtable parameterCollection = new Hashtable();
    parameterCollection.Add("name", lblDynamic.Text);
    ParameterEventArgs pe = 
       new ParameterEventArgs(parameterCollection);
    CustomEvent(this, pe);
    lblDynamic.Text = pe.ParameterCollection["name"].ToString();

I tried to create the delegate using Delegate.CreateDelegate, but somehow I was not able to do that. I think we can create the delegate using Delegate.CreateDelegate as well.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Technical Lead Thomson Reuters
India India
completed B.Tech in computer science, working as Technical Leader.

You may also be interested in...

Comments and Discussions

QuestionWhy would you want to do this? Pin
hain12-Dec-06 4:23
memberhain12-Dec-06 4:23 
AnswerRe: Why would you want to do this? Pin
karun12312-Dec-06 18:29
memberkarun12312-Dec-06 18:29 
GeneralRe: Why would you want to do this? Pin
sashisme12-Dec-06 20:12
membersashisme12-Dec-06 20:12 
GeneralCAB Pin
Urs Enzler11-Dec-06 21:56
memberUrs Enzler11-Dec-06 21:56 
GeneralRe: CAB Pin
karun12312-Dec-06 18:24
memberkarun12312-Dec-06 18:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180111.1 | Last Updated 6 Dec 2006
Article Copyright 2006 by karun123
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid