vendredi 10 juin 2016

Inserting code into C# methods right before compilation

I have a couple of methods that are being called from a WinForms app's entry point. These methods in turn call others and sometimes each other.

At the entry of each method, I have inserted code as follows:

public static bool IsDebug
{
    #if (DEBUG)
        return (true);
    #else
        return (false);
    #endif
}

public void SomeMethod ()
{
    if (IsDebug) { Logger.WriteMethodTrace(MethodBase.GetCurrentMethod().Name); }
}

There are two problems with this approach:

  • It is written by hand in each method.
  • It uses reflection which is too slow for frequently called methods.

.
REFLECTION: The new C# nameof(parameter) keyword works nicely for parameter names but I haven't found a similar construct for method names. I thought about creating some sort of a static dictionary to hold Type and MethodInfo details but there seems to be no way to extract the method name at runtime without reflection to use as a key in the dictionary.

WRITTEN BY HAND: Even if there was a solution to avoid reflection, each method would need to be altered by hand, which is tedious and error-prone. I was wondering if there is a way to insert a line of code just-in-time before compilation. Not sure is a VS extension or Roslyn would help here. Ideally, if auto-insertion is possible, the insertion should happen without actually modifying the source code.

Please note that analyzing the stack trace is not an option. I've been down that road and it is slow and unpleasant.

Any pointers/suggestions would be appreciated.





Aucun commentaire:

Enregistrer un commentaire