I'm trying to create a generic class that will fire an event whenever a method is called or a property is accessed or changed. It may also fire events in response to other changes or actions being taken, but for now, that'll be it.
In order to do so, I'd like to intercept every method call and every property access/change, but I have no way of knowing exactly which methods I'm handling. There's no given interface that defines every generic type T
I'll be working with, so I have to use reflection. Here's how I envision it (Trigger<T>
is the class, and generic
would be of type T
):
public Trigger()
{
this.generic = default(T);
foreach (MethodInfo m in generic.GetType().GetMethods())
{
// This is pseudocode, since I can't just set MethodInfo to a new method
m = delegate()
{
m.Invoke(this.generic, null);
if (MethodCalled != null)
MethodCalled(this, eventArgs /*imagine these are valid EventArgs*/);
};
}
}
I realize that I've grossly oversimplified the problem. First off, I'd have to deal with parameters. Second, you can't just override a method programmatically like that. And third, I haven't even started on properties yet. Plus, I'd have to be changing these things for only the object, not the entire type, so I'm not sure how that works either.
I've done my research, and all I find is confusing content. I realize that I'm somehow supposed to be using AOP, but I've never done anything other than OOP and procedural programming, so I'm rather lost in this dense jungle of knowledge. It sounds like I'll need to use PostSharp or Unity, but I still have no clue how after looking at all this, and this, and these two, and also this (all separate links, per word).
Is there any simpler way to do this? And can I even do it without using interfaces or predefined classes?
It's generics that make my problem particularly complicated. If I could just have a class inherit from T
, and then use a proxy to capture its method calls and property accesses/changes, then things would maybe be a tad simpler, though I still lack the fundamental understanding of AOP to do that. Any help you can provide would be much appreciated. If possible, please write your answer at a beginner level (though I know my OOP fairly strongly, like I said, I don't know the first thing about AOP).