0

I'm trying to implement my own aop-framework (like PostSharp). And stuck with one problem.

Say there is an attribute:

[AttributeUsage(AttributeTargets.Method)]
public class LogAttribute : Attribute
{
    public LogAttribute(int level, Type type)
    {
        // init fields...
    }
    public virtual void OnEnter(LogEventArg e)
    {
        // do some stuff...
    }
}

which is applied to one of the method:

[Log(3, typeof(Trace))]
static void TestMethod1(string s)
{
     // do some stuff...
}

And now the question: how to convert this to:

static void TestMethod1(string s)
{
     var t = new LogAttribute(3, typeof(Trace));
     t.OnEnter()
     // do some stuff...
}

I would like to strip attribute from method and not to use something like this:

var m = System.Reflection.MethodBase.GetCurrentMethod();
var attr = (LogAttribute) Attribute.GetCustomAttribute(m, typeof(Log));

With Mono.Cecil I have CustomAttributes.Constructor (MethodReference) and CustomAttributes.ConstructorArguments, which have 'Type' and 'Value' properties. But how to convert it to il instructions???

The only thing that I can write is:

il.InsertBefore(inst0, Instruction.Create(OpCodes.Newobj, attr.Constructor));

But how to pass arguments to this constructor, exactly as it was declared? I need a versatile option that is not tied to a specific constructor implementation.

O.K
  • 43
  • 3
  • The 'new Log' call in the processed TestMethod1 uses a different type than LogAttribute. You need to create a class Log somehow (and use it in the IL code). – Simon Mourier Mar 13 '13 at 17:59
  • It was a typo. Sorry. – O.K Mar 13 '13 at 18:26
  • att.ConstructorParameters[1] will contain a string representing the full assembly qualified type name of the Trace type. That's it. Doing this in a 100% generic way for any attribute represents some work, there's nothing magic (that's why some make a business out of it). I suggest you build what you want and have a look at it using .NET Reflector or ILSpy. You will basically have to reproduce that using IL. Postsharp also had community version with a source you can peek. Don't know if it's still the case. – Simon Mourier Mar 13 '13 at 18:57

0 Answers0