Friday, December 31, 2021

CompileTimeWeaver.Fody 3.3.3

 

Compile Time Weaver for AOP implementation

1. Introduce

DotNet Platform: NetStandard 2.0
Installation: 

PM> Install-Package CompileTimeWeaver.Fody

Different from runtime interception with dynamic proxy, this tool rewrites assembly at compile time, so that your code get these achievements that dynamic proxy based enhancement cannot give:
  • Much better performance, no dynamic proxy, no thread block or reflection at run time.
  • Directly instantiate your weaved classes with C# "new" operator
  • weave virtual methods/properties
  • weave static methods/properties
  • weave  extension methods
  • weave constructors
  • Add property changed notification to auto-properties

    2. Advice Based Programming Model

    Start with version 2, this tool support advice based programming model. Advice based programming model has these superiorities comparing to the old decorator based programing model in version 1:
    • Easy to intercept async method without thread blocking
    • Simple to control the flow and add “before”, “after”, “around” and “exception” advices
    • Allow to advise methods with parameters of reference type, value type and generic type, ref parameters and out parameters are allowed, too.

    2.1. Step-by-step Instruction

    Step 1) Create a C# project with VisualStudio.Net
    Step 2) Install nuget package CompileTimeWeaver.Fody

    Install NuGet package from https://www.nuget.org/packages/CompileTimeWeaver.Fody, you will see a FodyWeavers.xml file is added into project. The FodyWeavers.xml file content should have "CompileTimeWeaver" node as below, add it manually if the CompileTimeWeaver node is missing.
    <?xml version="1.0" encoding="utf-8"?>
    <Weavers>
      <CompileTimeWeaver />
    </Weavers>
    Step 3) Add MyAdvice class as below
    using CompileTimeWeaver;
    public class MyAdvice : AdviceAttribute
    {
        public override object Advise(IInvocation invocation)
        {
            // do something before target method is Called
            // ...
            Trace.WriteLine("Entering " + invocation.Method.Name);
    
            try
            {
                return invocation.Proceed();    // call the next advice in the "chain" of advice pipeline, or call target method
            }
            catch (Exception e)
            {
                // do something when target method throws exception
                // ...
                Trace.WriteLine("MyAdvice catches an exception: " + e.Message);
                throw;
            }
            finally
            {
                // do something after target method is Called
                // ...
                Trace.WriteLine("Leaving " + invocation.Method.Name);
            }
        }
    
        public override async Task<object> AdviseAsync(IInvocation invocation)
        {
            // do something before target method is Called
            // ...
            Trace.WriteLine("Entering async " + invocation.Method.Name);
    
            try
            {
                return await invocation.ProceedAsync(); // asynchroniously call the next advice in the "chain" of advice pipeline, or call target method
            }
            catch (Exception e)
            {
                // do something when target method throws exception
                // ...
                Trace.WriteLine("MyAdvice catches an exception: " + e.Message);
                throw;
            }
            finally
            {
                // do something after target method is Called
                // ...
                Trace.WriteLine("Leaving async " + invocation.Method.Name);
            }
        }
    }
    

    Step 4) Add [MyAdvice] to any of your class on class level or method level. 
    In the example below, [MyAdvice] is applied on MyClass class, and MyAdvice and MyClass can be in different assemblies.

    [MyAdvice]
    public class MyClass
    {
        public int Add(int x, int y)
        {
            return x + y;
        }
    
        public Task<int> AddAsync(int x, int y)
        {
            await Task.Delay(1000);
            return x + y;
        }
    }
    That is it. You don't need dynamic proxy such as Castle DynamicProxy, directly use you class as usual in C#, for example:
    var obj = new MyClass();
    int z = obj.Add(1, 2);
    z = await obj.AddAsync(1,2);
    The first time when you compile your project, FodyWeavers.xml and FodyWeavers.xsd are generated if they do not exist yet. The FodyWeavers.xml file content should have "CompileTimeWeaver" node as below, add it manually if the CompileTimeWeaver node is missing.
    <?xml version="1.0" encoding="utf-8"?>
    <Weavers>
      <CompileTimeWeaver />
    </Weavers>

    Debug your code, you will see your Add() method and AddAsync() method have been magically rewritten, and the output is as below:

    Entering .ctor...
    Leaving .ctor...
    Entering Add...
    Leaving Add...
    Entering AddAsync...
    Leaving AddAsync...

    2.2. Advice class specification

    • Inherits AdviceAttribute class, or
    • Inherits Attribute class and implements IAdvice interface

    2.3. Rules

    • When multiple advices are applied to a method, the advices are invoked as a pipe line, the Advise() or AdviseAsync() of the first advice is called first.
    • When an advice is applied to class level, it is identical to this advice is added on each constructor and each method.
    • Class level advices appears before all constructor/method level advices
    • Each advice is assigned an Order, it is the sequence number of the appearance in the type group.
    • Each advice on a recursive method is invoked only when the method was entered at the very first time, re-entrances don’t invoke the advice again, for performance reason.

    3. Built-in advices

    There are some built-in advices that you can immediately take advantage in your code, they are listed here.

    3.1. NotifyPropertyChangedAttribute

    When NotifyPropertyChangedAttribute is applied to a class, the class automatically implements INotifyPropertyChanged interface (if it is not implemented) and the setters of auto properties fire PropertyChanged event when the property values change.

    If you do not want a specific setter to fire event, just apply IgnoreNotifyPropertyChangedAttribute to the property, and the setter will not be rewritten.

    [NotifyPropertyChanged]
    public class MyClass //: INotifyPropertyChanged - optional
    {
        //public event PropertyChangedEventHandler PropertyChanged; - optional
    
        public string Name { get; set; }
        public int Age { get; set; }
    
        [IgnoreNotifyPropertyChanged]
        public string Password { get; set; }
    }
    One property change may cause the other property changes, DeterminedByPropertiesAttribute is to define dependancy relations between properties. In the code below, the change of property A fires property change events for property A, C and D, too.
    [NotifyPropertyChanged]
    public class MyClass //: INotifyPropertyChanged - optional
    {
        public int A { get; set; }
        public int B { get; set; }
    
        [DeterminedByProperties("A")]
        public int C => A + 1;
    
        [DeterminedByProperties("B","C")]
        public int D => B + C;
    }

    3.2. LoggingAttribute

    When LoggingAttribute is applied to a class or a method, the parameters of the constructor and methods are written into NLog, Log4Net or Serilog, depending on what logging package is enabled. [IgnoreLogging] is used to disable sensitive parameter logging. For example:

    [Logging]
    public class ClassWithLog
    {
        public static void MethodWithLog(
    		string userName,
    		[IgnoreLogging]string password,
    		int x,
    		int y)
        {
            ...
        }
    
        [IgnoreLogging]
        public static int MethodWithoutLog(int x, int y)
        {
            ...
        }
    }
    
    //The example application using Serilog calls ClassWithLog
    using Serilog;
        
    class Program
    {
        static void Main(string[] args)
        {
            Serilog.Log.Logger = new Serilog.LoggerConfiguration()
                                    .MinimumLevel.Debug()
                                    .Enrich.FromLogContext()
                                    .WriteTo.Console()
                                    .CreateLogger();
    
            ClassWithLog.MethodWithLog("Simon", "fdhasdewjsdfsdfe", 1, 2);
            ClassWithLog.MethodWithoutLog(1, 2);
    
            Serilog.Log.CloseAndFlush();
        }
    }

    When ClassWithLog.MethodWithLog method is called, you will see log messages as below, parameter values in log are from their ToString() method, and password parameter is not logged because of [IgnoreLogging] on it.

    MethodWithLog...
            userName: Simon
            x: 1
            y: 2
    MethodWithLog completed in 5 milliseconds.

    When ClassWithLog.MethodWithoutLog method is called, nothing is logged because it is decorated with [IgnoreLogging].

    3.3. ExceptionHandlerAttribute

    ExceptionHandler Attribute is an advice to consolidate exception handling logic into specific classes according to the exception types. In the example code below, the ApplicationExceptionHandler class defines ApplicationException handling logic and the IOExceptionHandler class defines IOException hanlding logic, you simply add ExceptionHandler decorations on the methods (HelloAsync as example below) to intercept the exceptions.

    public class MyClass
    {
        [ExceptionHandler(typeof(ApplicationException), typeof(ApplicationExceptionHandler))]
        [ExceptionHandler(typeof(IOException), typeof(IOExceptionHandler))]
        public async Task<int> HelloAsync()
        {
            await Task.Delay(1).ConfigureAwait(false);
            ...
            throw new ApplicationException();
            ...
            throw new IOException();
        }
    }
    
    internal class ApplicationExceptionHandler : IExceptionHandler
    {
        public bool HandleException(Exception e)
        {
            Trace.WriteLine(e.GetType() + " is caught");
            return false;
        }
    }
    
    internal class IOExceptionHandler : IExceptionHandler
    {
        public bool HandleException(Exception e)
        {
            Trace.WriteLine(e.GetType() + " is caught");
            return false;
        }
    }