jeudi 16 mars 2017

Comparing methods from MethodInfo and IMethodInvocation

I am using aspect-oriented programing to implement logging system. So, when the method being invoked I intercepting that call and get to that function:

    private IEnumerable<ILogMessage> GetLogMessageFromAttribute(IMethodInvocation input)
    {
        List<ILogMessage> messages = new List<ILogMessage>();
        var t = input.Target.GetType();
        var method = t.GetMethods()
                    .FirstOrDefault(m => m.ToString() == input.MethodBase.ToString());

        if (method != null)
        {
            var attributes = method.CustomAttributes
                             .Where(atr => atr.AttributeType == typeof(LogAttribute));

            foreach (var atr in attributes)
            {
                var logAttributeInstance =
                    (LogAttribute)Attribute.GetCustomAttribute(method, typeof(LogAttribute));

                messages.Add(MethodInfoTools.FillParametersDataInLogMessage(method, input,
                    logAttributeInstance.LogMessage));
            }
        }

        return messages;
    }

Methods can to be compared by own name, but it's can be overloaded and attribute can be different for these methods.

        var method = t.GetMethods()
                .FirstOrDefault(m => m.ToString() == input.MethodBase.ToString());

This way was good until I tried to intercept method with generic. In that case .ToString() returns:

System.String TestMethod2[String](System.Collections.Generic.IEnumerable`1[System.String], System.String)

and

System.String TestMethod2[T](System.Collections.Generic.IEnumerable`1[System.String], T)

Is there some way to find out what exact method was executed?





Aucun commentaire:

Enregistrer un commentaire