views:

548

answers:

3

I'm working on an EventRegistry that lets register some event handlers. Every time an event is raised it will check to see if there's any subscriber for that event and invoke them.

interface IEventRegistry
{
void Subscribe<TEventArgs>(Type eventType,EventHandler<TEventArgs> subscriber) where TEventArgs:EventArgs
void Publish<TEventArgs>(Type eventType,object sender,TEventArgs args) where TEventArgs:EventArgs
}

This way I should register my subscribers one by one.I think that it's a kind of job that can be automated using reflection.For example if there's a class of type Controller that has some OnXXX methods I'd like to subscribe them automatically :

foreach(var type in assembly.GetTypes())
{
if((typeof(Controller).IsAssginableFrom(type))
foreach(var methodInfo in type.GetMethods())
{
if(methodInfo.Name.StartsWith("On"))
     // Subscribe method
}

The question is that since I'm using a generic method to subscribe event handlers how is it possible to call it using a given type at runtime? Actually I don't know how to call Subscribe method of EventRegistry given some inputs by reflection at run time.

A: 

Use Type.InvokeMember to call methods on an instance. Or, if you're worried about performance, cache a set of Delegates that point to the procedures you need to call.

David Rutten
A: 

I think the best approach would be using a custom attribute since then you can look for methods with the specific attribute at runtime.

Taylor Leese
I can use attributes to find my event handlers methods but still I have the problem to subscribe them.Actually I don't know how to call Subscribe method of EventRegistry at runtime
Beatles1692
A: 

I found my answer here

Actually it seems that there are some MakeGenericXXX methods that help us to work with generics using reflection.

Beatles1692