How to start with NetAspect
Show the sample class to divide two numbers
This class is in a C# project named Math.csproj
public class Computer { public int Divide(int a, int b) { return a / b; } }
To use NetAspect in your .Net projects
Just add the NetAspect Nuget package to the Math.csproj
Download the latest version of NetAspect Here and unzip it in the directory you want. For example : C:\NetAspect.
Now edit the Math.csproj project with an XML Editor and put the following line :
<Import Project="C:\NetAspect\NetAspect.targets" Condition="Exists('C:\NetAspect\NetAspect.targets')" />
This line must be after the following line :
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
Imagine we want to log when an exception occured in our Divide method
To handle the exception, we must create an aspect :
public class LogAttribute : Attribute { public bool NetAspectAttribute = true; public static StringWriter writer = new StringWriter(); public void OnExceptionMethod() { writer.Write("An exception !"); } }
To indicate to the weaver that our Divide Method must handle our aspect
Now we must weave our Divide method to the aspect. That's why, we add the aspect attribute to the method :
public class Computer { [Log] public int Divide(int a, int b) { return a / b; } }
Just see the results !
Now you can write and run the following test :
[TestFixture] public class MathAspectTest { [Test] public void CheckDivideByZero() { var computer = new Computer(); try { computer.Divide(12, 0); } catch (Exception) { Assert.AreEqual("An exception !", LogAttribute.writer.ToString()); } } }