Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / C#

Intercepting Console.WriteLine and Other Third-Party Method Calls with LinFu.AOP 2.0

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
4 May 2011LGPL32 min read 14.9K   7
Intercepting Console.WriteLine and Other Third-Party Method Calls with LinFu.AOP 2.0

ConsoleInterceptor

Worth a Thousand Words

In case you are wondering, yes, that is a screenshot of LinFu.AOP intercepting calls to Console.WriteLine() at runtime.

One of the more useful things that LinFu.AOP can do is intercept calls to third-party assemblies that aren't necessarily under your control. In fact, LinFu makes it so easy that all you have to do to make the interception happen is add the reference to LinFu like the following lines to your CSProj file just like I did with my SampleLibrary.csproj file:

XML
<PropertyGroup>
  <PostWeaveTaskLocation>
    $(MSBuildProjectDirectory)\$(OutputPath)\..\..\..\lib\LinFu.Core.dll
  </PostWeaveTaskLocation>
</PropertyGroup>
<UsingTask TaskName="PostWeaveTask" AssemblyFile="$(PostWeaveTaskLocation)" />
<Target Name="AfterBuild">
  <PostWeaveTask TargetFile="$(MSBuildProjectDirectory)\
	$(OutputPath)$(MSBuildProjectName).dll" 
                 InterceptAllMethodCalls="true" />
</Target>

'Automagically' Delicious

Once you reload and rebuild the solution, LinFu.AOP will automatically modify your code after the build runs so that you can intercept it at runtime. LinFu does this by adding hooks to your code so you can change it as the program is running. In this case, I casted the modified BankAccount class to an IModifiableType instance so that I could add my custom ConsoleInterceptor instance:

C#
// Create the BankAccount class just like normal...
var account = new BankAccount(100);
// Notice how LinFu.AOP automatically implements IModifiableType 
// so you can intercept/replace method calls at runtime
var modifiableType = account as IModifiableType;
if (modifiableType != null)
modifiableType.MethodCallReplacementProvider = new WriteLineMethodReplacementProvider();

account.Deposit(100);

The WriteLineMethodReplacementProvider class, in turn, determines the method calls that should be intercepted at runtime:

C#
public class WriteLineMethodReplacementProvider : IMethodReplacementProvider
{
    public bool CanReplace(object host, IInvocationInfo info)
    {
        var declaringType = info.TargetMethod.DeclaringType;
        if (declaringType != typeof(System.Console))
        return false;

        // We're only interested in replacing Console.WriteLine()
        var targetMethod = info.TargetMethod;
        return targetMethod.Name == "WriteLine";
    }

    public IInterceptor GetMethodReplacement(object host, IInvocationInfo info)
    {
        return new ConsoleInterceptor();
    }
}

Choosing Which Methods to Intercept

As you can see from the example above, this class ensures that only calls to Console.WriteLine() are ever intercepted. The ConsoleInterceptor itself is responsible for replacing and intercepting the Console.WriteLine() method itself:

C#
public class ConsoleInterceptor : IInterceptor
{
    public object Intercept(IInvocationInfo info)
    {
        var targetType = info.TargetMethod.DeclaringType;
        var target = info.Target;
        var targetMethod = info.TargetMethod;
        var arguments = info.Arguments;

        Console.WriteLine("Intercepted method named '{0}'", targetMethod.Name);

        // Call the original WriteLine method
        targetMethod.Invoke(null, arguments);

        // Console.WriteLine doesn't have a return value so it's OK to return null)
        return null;
    }
}

The most interesting part about the code example is how LinFu.AOP adds the method call hooks without touching a single line of the source code. All of the IL rewriting is done behind the scenes so you won't have to worry about the gory details of using an AOP framework in your legacy code. The beauty of this approach is that it allows you to intercept any method call, even if that method call is a part of the .NET base class libraries.

You can find the LinFu.AOP.Examples library here at Github.

Note: Please intercept BCL method calls responsibly.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Software Developer (Senior) Readify
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionthis post is useless with EF code first Pin
ron0123423-Jul-13 20:08
ron0123423-Jul-13 20:08 
QuestionQuestion Pin
ron0123422-Jul-13 13:54
ron0123422-Jul-13 13:54 
GeneralSomething is missing? Pin
caloggins9-May-11 7:57
caloggins9-May-11 7:57 
GeneralRe: Something is missing? Pin
Philip Laureano9-May-11 14:00
Philip Laureano9-May-11 14:00 
JokeRe: Something is missing? Pin
caloggins10-May-11 0:42
caloggins10-May-11 0:42 
GeneralRe: Something is missing? Pin
ron0123423-Jul-13 13:11
ron0123423-Jul-13 13:11 
GeneralGood stuff Pin
RugbyLeague4-May-11 3:24
RugbyLeague4-May-11 3:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.