Search code examples
c#fody

How to pass only some properties of an object in method parameters to Fody/MethodTimer Interceptor


I want to log the execution time for my methods by Fody/MethodTimer.

I Cannot pass only some properties of my methods' parameters (which are a class type).

My Method :

[Time("'{obj.EventId}'")]
private static void testFody(TestClass obj)
{
     for (int i = 0; i < 100; i++)
     {
          Console.WriteLine($"This is : {i }");
     }
}

public class TestClass
{
    public Guid EventId { get; set; }

    public string prop1 { get; set; }

    public int prop2 { get; set; }
}

When I run this code I get the following error :

Could not process 'System.Void TestCurrentEPCIS.Program::testFody(TestCurrentEPCIS.TestClass)' because the format uses 'obj.EventId' which is not available as method parameter.

And when I pass the object itself as following, it passes obj.ToString() to Interceptor class:

[Time("'{obj}'")]
private static void testFody(TestClass obj)

How can I pass some properties of my obj parameters to Interceptor??


Solution

  • According to the documentation, this is currently something that is not supported:

    Note 1: sub-properties are not (yet?) supported.

    The weaver only supports two types of arguments via the attribute:

    The following values are allowed:

    • Any parameter name (e.g. {fileName})
    • {this} (calls ToString() on the instance itself) Note that this is not available on static methods, the weaver will throw an error if being used in a static method

    (emphasis mine)

    It seems that the only thing that you could do is include the properties in an overridden ToString method.

    The weaver is open-source. If you have time that you can dedicate to this, you may consider forking the project and making the necessary updates. A good place to start seems to be the ParameterFormattingProcessor class which is using a basic Regex to identify the parameter name.