• Home /
  • Blog /
  • Improved logging using Castle DynamicProxy and StructureMap with log4net
Improve Logging

Improved logging using Castle DynamicProxy and StructureMap with log4net

In the previous post I explained how to improve logging abilities of your application using AOP abilities of Microsoft Policy Injection Application Block, but you can do the same using different frameworks. In this post I will explain how to intercept calls to methods of your class using Castle DynamicProxy for wrapping your class in proxy and StructureMap to resolve dependency. All logging will be done using log4net instead of Console.WriteLine()

Prerequisites for logging using log4net and aspect oriented programming

Let's create console application and add required references using Nuget

Install-Package Castle.Core 

Install-Package structuremap Install-Package log4net

Now create interface and implementation of Repository which will be our test object and let StructureMap know what class to return for our interface

Now we have to intercept creating of our class and wrap our class in proxy, we will do it using StructureMap intercepting feature. To create interceptor using StructureMap we have to create a new class and inherit it from TypeInterceptor interface. Then you have to implement MatchType and Process methods. For now we are not interesting in MatchType method, so we will always return true, but inside of Process method we have to wrap the instance of our class in Proxy class using DynamicProxy object from Castle project. Creating proxy is pretty simple, you create an instance of the ProxyGenerator class and call CreateInterfaceProxyWithTargetInterface and the last parameter of the method will be our logging interceptor which will intercept calls to methods of the class So as you see we doing interception two times, first time with StructureMap we intercept creating of the instance of our class and wrapping our class in proxy and second time we are intercepting calls to methods of our class using DyanamicProxy and it’s the place where we will log our input parameters and output result of calling method. Let’s StructureMap know then it should use our interceptor

The implementation of castle dynamicProxy interceptor is similar to Policy Application block interceptor from previous post

The difference are, in this case we use log4net to log information As a result we get the following when run our application

All source code to this post is available on Github

Yaplex - Freelance developer - white logo on black background

Yaplex ® is a custom software development company located in Mississauga, Ontario. Yaplex was founded in 2013 and provides website development, mobile development, and custom .NET software development services.

Contact Information

Mississauga, ON, Canada
Phone: +1 647 328 3809
Email: hello@yaplex.com