Compile time IL weaver for AOP implementation.
$ dotnet add package CompileTimeWeaver.FodyInstallation:
PM> Install-Package CompileTimeWeaver.Fody
Different from runtime interception with dynamic proxy, this tool rewrites assembly at VisualStudio/MSBuild build time, so that your code get these achievements that dynamic proxy based enhancement cannot give:
Start with version 2, this tool support only advice based programming model. An advice is created in C# as an attribute derived from AdviceAttribute class.
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().ConfigureAwait(false); // asynchroniously call the next advice in 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);
}
}
}
[MyAdvice]
public class MyClass
{
public int Add(int x, int y)
{
return x + y;
}
public Task<int> AddAsync(int x, int y)
{
await Task.Dely(1000).ConfigureAwait(false);
return x + y;
}
}
The MyAdvice class and MyClass class can be in different assemblies. Now use your MyClass as below:
var obj = new MyClass();
int z = obj.Add(1, 2);
z = await obj.AddAsync(1,2);
Debug your code, you will see your Add() method and AddAsync() method were magically rewritten, and the output is as below:
Entering .ctor... Leaving .ctor... Entering Add... Leaving Add... Entering AddAsync... Leaving AddAsync...
The first time when you compile your project, FodyWeavers.xml and FodyWeavers.xsd are generated if they do not exist yet. FodyWeavers.xml content likes this below. Usally you do not need to change the generated FodyWeavers.xml file at all.
<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<CompileTimeWeaver />
</Weavers>
There are some built-in advices that you can take advantage in your code.
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, 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 used 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.
[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;
}
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
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); //parameters except password are logged
ClassWithLog.MethodWithoutLog(1, 2); //parameters are not logged
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].
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 IOnExceptionHandler 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;
}
}