Wednesday, February 6, 2019

CompileTimeWeaver.Fody V3.1.7

(Please reference to document for newer version 3.3.3 with bug fix and enhancements)

The nuget package 

PM> Install-Package CompileTimeWeaver.Fody

.Net Platforms

  • Framework 4.6.1
  • NetStandard 2.0

Compile time IL rewriting tool for AOP implementation

Different from runtime interception with dynamic proxy, this tool rewrites assembly at VisualStudio.Net build 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 new operator
  • weave virtual methods/properties
  • weave static methods/properties
  • weave  extension methods
  • weave constructors

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.

Your Code

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 first time when you compile MyClass class, FodyWeavers.xml and FodyWeavers.xsd are generated if they do not exist yet. FodyWeavers.xml content likes this below:
<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
  <CompileTimeWeaver />
</Weavers>
If (1) your MyClass and MyAdvice are in different assemblies and (2) your target platform is netstandard, you need
to manually add the full name of MyAdvice class into AdviceAttributes property of CompileTimeWeaver section in FodyWeavers.xml file
as below (suppose the namespace of MyAdvice is Advices here):
  <CompileTimeWeaver AdviceAttributes="Advices.MyAdvice" />
To add more advice classes into AdviceAttributes property, seperate them with ‘|’ delimitor, for example: AdviceAttributes=“Advices.MyAdvice1|Advices.MyAdvice2”.
You do not have to change this file if your target is .net Framework or MyClass and MyAdvice are in same assembly.

Notes:

  • 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.

7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi Dear Simon; Last year, you have introduced me to the joyful world of AOP, ILWeaving and Compiler add-in for Fody. I am very proud of you and your contributions with this super plugin! You saved me from a lot of unnecesary works :-)

    ReplyDelete
  3. Namespace is not available![.Net5 ConsoleApp]

    Fody: An unhandled exception occurred:
    Exception:
    Failed to execute weaver C:\Users\BPPX\.nuget\packages\compiletimeweaver.fody\3.1.7\build\..\netclassicweaver\CompileTimeWeaver.Fody.dll
    Type:
    System.Exception
    StackTrace:
    在 InnerWeaver.ExecuteWeavers() 位置 C:\projects\fody\FodyIsolated\InnerWeaver.cs:行号 185
    在 InnerWeaver.Execute() 位置 C:\projects\fody\FodyIsolated\InnerWeaver.cs:行号 108
    Source:
    FodyIsolated
    TargetSite:
    Void ExecuteWeavers()
    Could not find 'CompileTimeWeaver.IAdvice'.
    Type:
    Fody.WeavingException
    StackTrace:
    在 Fody.TypeCache.FindType(String typeName) 位置 C:\projects\fody\FodyHelpers\TypeCache.cs:行号 115
    在 CompileTimeWeaver.Fody.ModuleWeaver.Execute() 位置 C:\My\CompileTimeWeaver\CompileTimeWeaver.Fody\ModuleWeaver.cs:行号 43
    在 InnerWeaver.ExecuteWeavers() 位置 C:\projects\fody\FodyIsolated\InnerWeaver.cs:行号 181
    Source:
    FodyHelpers
    TargetSite:
    Mono.Cecil.TypeDefinition FindType(System.String)
    CompileTimeWeaverFodyTest 1

    ReplyDelete
    Replies
    1. This is a installation problem existing in sdk project only, you can manually add reference to packages\compiletimeweaver.fody\3.1.7\lib\netstandard2.0\CompileTimeWeaver.dll into your project, you can find this assemble in the directory where the nuget package was downloaded to.

      Delete
    2. This problem was fixed, please try version 3.3.3, there docuemnt is at https://brooksidebeauty.blogspot.com/2021/12/compiletimeweaverfody-333.html

      Delete