Method Interception using Reflection in C# -
i wrote abstract class uses reflection find fields marked attribute in constructor, this:
[attributeusage(attributetargets.field)] public class trackedfield : attribute {} public class atrackedobject { public atrackedobject() { type objtype = this.gettype(); foreach(fieldinfo f in objtype.getfields()) { if(f.isdefined(typeof(trackedfield)), false)) { //add field list keep tabs on periodically } } } }
what do, is:
- create attribute, trackedmethod
- in constructor, in same fashion trackedfields, find methods tagged trackedmethod
- change method when gets called, method inside atrackedobject gets called first or instead, either replacing method entirely or injecting code it, without breaking ability @ least see original method call was, including parameters
- no third-party libaries, , should .net 3.5 compatible
i have seen number of se threads discussing how this, , of answers relied on being able use third party library - however, none of questions seemed match use case - can ensure 100% every object needs have methods tracked inherit class tracking.
i don't know sure possible, wondering since ioc/aop libraries postsharp , others exist, surely must operate kind of mechanism - assume reflection.emit plays part - what, , how?
here similar questions, did not have seemed me answers specific scenario, or relied on third party libraries:
custom-attribute-to-process-info-before-a-method-is-called
how-do-i-intercept-a-method-call-in-c (this helpful, missing crucial component of how inject code
is there way make technique (attribute -> base class constructor -> reflection -> method interception) viable?
could work need?
[attributeusage(attributetargets.field)] public class trackedfield : attribute { } public class atrackedobject { public atrackedobject() { type objtype = this.gettype(); foreach (fieldinfo f in objtype.getfields()) { if (f.isdefined(typeof(trackedfield), false)) { if (f.fieldtype == typeof(action)) { var currentvalue = f.getvalue(this) action; action newvalue = () => { console.writeline($"tracking {f.name}"); currentvalue.invoke(); }; f.setvalue(this, newvalue); } } } } [trackedfield] public action somemethod = () => console.writeline("some method called"); }
this done simple action
property extended use func<>
edit: forgot include usage , output.
usage:
static void main(string[] args) { var obj = new atrackedobject(); obj.somemethod(); console.read(); }
output:
tracking somemethod method called
Comments
Post a Comment