AoP with castle part 4–Adding AoP to service oriented App

Previous Parts of the series

Part 1 – The basic of interception
Part 2 – Selecting Methods to intercept
Part 3 – The first interceptor

AOP works great if you have clear interfaces where you want to put some standard and shared logic, and a Service Oriented Application falls in this category. A service is just a bunch of methods that will share some common behavior like: Validation, logging, Security etc etc, so it is a good strategy to create interceptors for each one of this behavior and associate them to service classes. The good point is that Castle has a dedicated facility to integrate with WCF, that basically is able to resolve WCF server classes with castle. Setting up such a facility is really simple, and you can follow the instruction found on castle’s site.

Surely the first aspect you can add to a Service is the ability to log every call (seen in previous post), but you can also centralize some other operations such as: Exception management or NHibernate session handling.

Validation is another operations that benefit from being applied with AOP. In SOA scenario, services will usually accepts dto objects containing all data needed to accomplish a certain operation. Dto are used because services usually exposes a coarse grained interface to limit the number of calls needed to accomplish a business operation. This is because each call is usually made across a network and latency forces you to limit number of calls, this lead to a common pattern where a business operation is implemented with a single call accepting a dedicated dto. In our example, to create a new album we need to pass an Album object (in real scenario this object will have a list of songs). It is not a real dto because it is a Domain Object, but for this simple example think that it is a dto J, I’ve decorated entity properties with validation attributes.

   1: [DataMember]

   2: [Required("La proprietà Titolo è richiesta")]

   3: [RangeLength("Il titolo deve essere compreso tra 1 e 50 caratteri", 1, 50)]

   4: public virtual string Title { get; set; }


   6: [Required("La proprietà Autore è richiesta")]

   7: [RangeLength("L'autore deve essere compreso tra 1 e 50 caratteri", 1, 50)]

   8: [DataMember]

   9: public virtual string Author { get; set; }

Those attributes are used by a validation library that is able to take an object as input and tell us if it is valid or not. Creating a validation aspect on this structure is straightforward because you can simply validate all objects that are not primitive one, or you can make all of your dto implement a marker interface, or you can use convention over configuration. The important concept is that a service call accepts one or more dto and each one support validation.

   1: public class ValidatorAspect : IInterceptor

   2: {

   3:     #region IInterceptor Members


   5:     private DotNetMarche.Validator.Core.Validator validator = new Validator();


   7:     public void Intercept(IInvocation invocation)

   8:     {

   9:         foreach (object argument in invocation.Arguments)

  10:         {

  11:             if (!argument.GetType().IsPrimitive) validator.CheckObject(argument);

  12:         }

  13:         invocation.Proceed();

  14:     }


  16:     #endregion

  17: }

Method CheckObject() takes an object as argument, and raise a ValidationException if the object does not satisfy some validation rule. With this simple interceptor I’m sure that each call with invalid dto will throw an exception bringing me two distinct advantages: the first is that no invalid object will ever reach a service method and the other one is that the exception raised carries validation errors, so the client is able to understand why the call is failed. Suppose that the Album.Name is a required property, without validation here is the exception returned from a call with invalid arguments.

not-null property references a null or transient valueMusicStore.Entities.Album.Title

Server stack trace: at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter) at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)Now we have a service that when called with an invalid data will return some useful exception that tells us what exactely is the error.

Clearly this a NHibernate exception and the caller probably does not know anything about NH to understand why the call failed. Moreover it is not a good strategy to let all exceptions flow to caller, especially for security reason.

Now activate validator interceptor and look at what is happening when you invoke the SaveAlbum()with an empty dto: now a ValidationException is raised and the message is.

Title property length should be in range 1-50

Title property is required.

Author property is required.

Author property length should be in range 1-50

This is a really clear exception that can be used from the client to understand why the call failed. Now the next step is send back exception data in a way that is more WCF compliant, this is needed because the above examples where run with this configuration

   1: includeExceptionDetailInFaults="true"

this is a bad practice, because exceptions should not flow to the caller, but if you set this value to false, when an exception occurs on the server, the client gets

The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults ….

WCF has a specific technique to send back exception data to the caller in a Service Oriented way, you should specify with an attribute witch object will carry exception data to the caller, so whenever an exception occurs, the caller will receive a valid response object with data.

   1: [OperationContract, FaultContract(typeof(FaultDetail))]

   2: int Save(Album album);

As you can see, this declaration informs the client that in case of fault, service will return failure details in an object of type FaultDetail.


When an exception happens, server code should throw a very specific type of exceptions of type FaultException with the type of exception data as Type parameter, as showed with this code:

   1: throw new FaultException<FaultDetail>(

Thanks to AOP we can wrap every exception of the service and create specific data to be sent back to the client, categorizing types of error. Here is the code.

   1: public void Intercept(IInvocation invocation)

   2: {

   3:     try

   4:     {

   5:         invocation.Proceed();

   6:     }

   7:     catch (FaultException<FaultDetail>)

   8:     {

   9:         throw;

  10:     }

  11:     catch (ValidationException vex)

  12:     {

  13:         throw new FaultException<FaultDetail>(new FaultDetail(vex), "Validation Failed");

  14:     }

  15:     catch (Exception ex)

  16:     {

  17:         Logger.Error("Intercepted generic exception on service call", ex);

  18:         throw new FaultException<FaultDetail>(

  19:             new FaultDetail(ex), new FaultReason(ex.Message));

  20:     }

  21: }

As you can see, if the calls throws a FaultException<FaultDetail> we can simply rethrow (someone else in the stack already packed a correct WCF exception message), but if a validation exception occurs we should pack all validation exception in a FaultDetail object and throw back to the caller. Finally, for every generic exception we can simply pack exception information in FaultDetail object and tells to caller that something gone wrong.

Another interesting interceptor is used to manage the unit of work for single WCF call. For each call it simply check if a session was already created for that call, if not, it creates one and begin a transaction. It catch also all exception and if an exception occurs, it simply rollback the transaction and rethrow.

The advantage of using AoP is the ability to inject common logic in service pipeline to handle common aspect: validation, session management and error handing in a unique and common position.


AOP With castle–Part 3-The first interceptor

Previous Parts of the series

Part 1 – The basic of interception
Part 2 – Selecting Methods to intercept

Usually the very first interceptor you can build with an AOP framework is the “logger Interceptor”, because it is simple and useful, especially when you expose some services with WPF. Consider this scenario: you expose some services with WPF, sometimes people tell you that your services have bugs or they encountered an exception, or they get wrong result, etc. In this situation you receive information like:

“I got exception from your service”, and no more details, so you need to spent time trying to understand what is happened.

Since this is probably the most detailed information you can have from the customer J, having a good log system is vital. You need to identify what is happened and you need to build a system to log:

  • every call to service methods
  • all parameters value for the call
  • return value and exception that are raised (if one).

The goal is having a full and configurable log of what is happened in the service to retrace exception and problems experienced by users. Now wait and avoid the temptation to modify every service class in the system adding log calls since you can use AOP to add logging capability to each intercepted service. Such an interceptor is really simple to build, and with few lines of code you can log every call made to a function of intercepted class.

As a requisite, you need to instantiate wcf service classes with CastleIntegration facility and Logging integration facility; thanks to these two facilities you are able to resolve the service class with castle (thus adding interceptor), and use the log4net integration to avoid hardcoding logging to specific target, like file etc. The good point in log4Net castle integration is the ability to declare a dependency to a generic ILogger interface. This feature can be used in the Logging Interceptor.

   1: public class LogAspect : IInterceptor

   2: {

   3: public LogAspect(ILogger logger)

   4: {

   5:     Logger = logger;

   6: }


   8: public ILogger Logger { get; set; }

Castle log4net facility is able to resolve the ILogger dependency with an implementation of log4net logger that has a name equal to the name of the class that declares dependency. This is the most important point, because in the above code, the logger will have the name MusicStore.Aspects.Log.LogAspect, and this permits me to change the log setting for each single class in the system. The interceptor will need also a little helper function to create a string that dump every details of the call.

   1: public static String CreateInvocationLogString(IInvocation invocation)

   2: {

   3:     StringBuilder sb = new StringBuilder(100);

   4:     sb.AppendFormat("Called: {0}.{1}(", invocation.TargetType.Name, invocation.Method.Name);

   5:     foreach (object argument in invocation.Arguments)

   6:     {

   7:         String argumentDescription = argument == null ? "null" : DumpObject(argument);

   8:         sb.Append(argumentDescription).Append(",");

   9:     }

  10:     if (invocation.Arguments.Count() > 0) sb.Length--;

  11:     sb.Append(")");

  12:     return sb.ToString();

  13: }

Since parameters of the service could be complex objects I’m dumping information with an helper function that is able to include every detail of a class.

   1: private static string DumpObject(object argument)

   2: {

   3:     Type objtype = argument.GetType();

   4:     if (objtype == typeof(String) || objtype.IsPrimitive || !objtype.IsClass)

   5:         return objtype.ToString();

   6:     return DataContractSerialize(argument, objtype);

   7: }

I want to keep the code simple, if the object type is not primitive I use DataContractSerialize to dump the content in XML format. Once everything is in place I need to insert the call to the logger in the appropriate point.

   1: public void Intercept(IInvocation invocation)

   2: {

   3:     if (Logger.IsDebugEnabled) Logger.Debug(CreateInvocationLogString(invocation));

   4:     try

   5:     {

   6:         invocation.Proceed();

   7:     }

   8:     catch (Exception ex)

   9:     {

  10:         if (Logger.IsErrorEnabled)  Logger.Error(CreateInvocationLogString(invocation), ex);

  11:         throw;

  12:     }

  13: }

Before each call to the logger object I first check if the appropriate level of logging is enabled. This technique is useful to avoid loss of performance when log is not enabled; if the debug level is set to warn, the Logger.Debug will not log anything and the CreateInvocationLogString will build the log string for nothing, losing processor time with no benefit. To avoid this loss you can issue a call to Logger.IsDebugEnabled to avoid entirely the call to logging function.

Now suppose that the caller pass an invalid object to method Save() of MusicStoreService, the user will see a message telling that a service error is occurred, but now I’m able to check the log to understand exactly what is happened. Here is the log of a call that raise an exception.

   1: 2010-07-24 10:12:28,320 ERROR MusicStore.Aspects.Log.LogAspect - Called: MusicStoreService.Save(<Album xmlns:i="" xmlns="">

   2:   <Id>0</Id>

   3:   <Author

   4:     i:nil="true" />

   5:   <Genre

   6:     i:nil="true" />

   7:   <Image

   8:     i:nil="true" />

   9:   <Label

  10:     i:nil="true" />

  11:   <Note

  12:     i:nil="true" />

  13:   <PublicationDate>0001-01-01T00:00:00</PublicationDate>

  14:   <Title

  15:     i:nil="true" />

  16:   <Tracks

  17:     i:nil="true" />

  18: </Album>)

  19: NHibernate.PropertyValueException: not-null property references a null or transient valueMusicStore.Entities.Album.Title

  20:    at NHibernate.Engine.Nullability.CheckNullability(Object[] values, IEntityPersister persister, Boolean isUpdate)

  21:    at NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)

  22:    at NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object entity, Object id, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)

  23:    at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)

From this log I understand that an invalid object is passed to the service, the property Album.Title is required in the database, but the user passed a property with null value. Since log4net is really flexible I’m able to dump this information to a file, to a database, to network or with mail. You can as example send a mail each time an exception occurs, so you are immediately notified if something in the service is not going well.

This logger can be improved a little bit because the name of the logger is always MusicStore.Aspects.Log.LogAspect for each wrapped service. This is not really a problem, but I prefer to have the ability to configure logging differently for each service; in real product with a lot of services, this is a key requiremente. The interceptor can be changed in this way:

   1: public class LogAspect : IInterceptor

   2: {

   3:     public LogAspect(ILoggerFactory loggerFactory)

   4:     {

   5:         LoggerFactory = loggerFactory;

   6:         Loggers = new Dictionary<Type, ILogger>();

   7:     }


   9:     public ILoggerFactory LoggerFactory { get; set; }


  11:     public Dictionary<Type, ILogger> Loggers { get; set; }

Now the interceptor declares a dependency to an ILoggerFactory and not to a concrete ILogger, and caches a list of ILogger object based on type. The result is a concrete ILogger object for each wrapped type.

   1: public void Intercept(IInvocation invocation)

   2: {

   3:     if (!Loggers.ContainsKey(invocation.TargetType))

   4:     {

   5:         Loggers.Add(invocation.TargetType, LoggerFactory.Create(invocation.TargetType));

   6:     }

   7:     ILogger logger = Loggers[invocation.TargetType];

   8:     if (logger.IsDebugEnabled) logger.Debug(CreateInvocationLogString(invocation));

instead of using the same logger, we first check if we had already created a logger for a given type, if false we use the ILoggerFactory to create the logger and cache it to an inner dictionary. If we send an invalid object again to the service the head of the log is.

   1: 2010-07-24 10:27:30,783 DEBUG MusicStore.WebService.MusicStoreService - Called: MusicStoreService.Save(..

Now the name of the logger is equal to the name of the concrete service class and you have created a simple logging system that can:

  1. Add transparently to each service class without needing a single line of code
  2. Change logging level for each concrete class of the service.

Happy intercepting with Castle :)


Cache layer

Thanks to AOP concept, creating a cache layer that is transparent to the caller is not a big deal. I have a piece of code that in a loop calls this method

   1: ClientCompetitor competitor = Repository.ClientCompetitor.GetByCriteria(

   2:     Query.CreateEq("AssociatedClient", clieid))

   3: .SingleOrDefault();


This is based on a standard implementation of repository and a Specification Pattern as a query model. With nhibernate profiler I see that during the execution of this task, a lot of identical query are issued, because it gets called around 1000 times always with the same clieid.

Now before changing the code of the class to store in a dictionary<ClieId, ClientCompetitor> cached result, I like to handle this with a transparent cache layer used with AOP. This could be achieved registering this interceptor.

   1: <component

   2:         id="RepositoryCache"

   3:         service="Castle.Core.Interceptor.IInterceptor, Castle.Core"

   4:         type="xxx.BaseServices.Castle.Cache2Interceptor, xxx.BaseServices"

   5:         lifestyle="transient">

   6:     <parameters>

   7:         <invocationCache>${WindowsCache}</invocationCache>

   8:         <Rules>

   9:             <dictionary>

  10:                 <entry key="ClientCompetitor.*GetByCriteria">.classname(ClientCompetitor) .absolute(600)</entry>

  11:             </dictionary>

  12:         </Rules>

  13:     </parameters>

  14: </component>

I simply create a Cache2Interceptor object that has a property called Rules to define regular expression to specify witch methods I want to apply cache to. With this configuration I ask to put cache in ClientCompetitor repository and with GetByCriteria method. The cache component use the Specification Pattern object for retrieving the key to the real cache implementation, and I tell cache component that the classname is (ClientCompetitor). The className is used because I can register other method as cache invalidator, as an example I can tell that the method Save of ClientCompetitor repository will invalidate the entire ClientCompetitor class.

When the interceptor is configured, I can simply tell castle to apply it to ClientCompetitor repository class, and the game is done.

Then I rerun the code and only one query gets issued, with no modification to the original code.


Aop With castle Part 1

I made a session about Aop with castle in a Italian workshop oranized by our association DotNetMarche, and some of the attendee asked me to publish the material in my blog. So I decided to start to publish all material in english language.


If you look at canonical terms of aop you can recognize standard ones such as Aspect, JointPoint, PointCut , but if you look at castle infrastructure you could not find any of these. This does not means that castle does not supports AOP, but is a clue that Castle handles AOP with different point of view respect to other frameworks.

AOP is based on the concept of Weaving, and castle does this with the excellent Castle.DynamicProxy2 library, that is used by Castle Windsor to manage crosscutting concerns with the concept of Interceptors and the interface IInterceptor. The basic of castle is the ability to create a component that is able to intercept every calls to methods and or properties of an interface, and deciding with Windsor configuration where to apply this interceptor. At the most basic level, let consider this simple interface and its implementation.

   1: public interface ISomething

   2: {

   3:     Int32 Augment(Int32 input);

   4:     void DoSomething(String input);

   5:     Int32 Property { get; set; }

   6: }


   8: class Something : ISomething

   9: {

  10:   #region ISomething Members


  12:   public int Augment(int input)

  13:   {

  14:      return input + 1;

  15:   }


  17:   public void DoSomething(string input)

  18:   {

  19:      Console.WriteLine("I'm doing something: " + input);

  20:   }


  22:   public int Property

  23:   {

  24:      get;

  25:      set;

  26:   }


  28:   #endregion

  29: }

Now I want to be able to intercept every call and log it; the solution in castle is to create an interceptor like this one.

   1: public class DumpInterceptor : IInterceptor

   2: {

   3:     #region IInterceptor Members


   5:     public void Intercept(IInvocation invocation)

   6:     {

   7:         Console.WriteLine("DumpInterceptorCalled on method " + invocation.Method.Name);

   8:         invocation.Proceed();

   9:         if (invocation.Method.ReturnType == typeof(Int32))

  10:         {

  11:             invocation.ReturnValue = (Int32)invocation.ReturnValue + 1;

  12:         }

  13:         Console.WriteLine("DumpInterceptor returnvalue is " + (invocation.ReturnValue ?? "NULL"));

  14:     }


  16:     #endregion

  17: }

As you can see, the IInterceptor interface has only a method, called Intercept, that gets called whenever a function or property of the wrapped interface is called. Now we need only to instruct castle to intercept an object with this interceptor, here is the solution with standard XML config files.

   1: <component id="BasicElement"

   2:         service="TheBasicOfAopWithCastle.TestClasses.ISomething, TheBasicOfAopWithCastle"

   3:         type="TheBasicOfAopWithCastle.TestClasses.Something, TheBasicOfAopWithCastle"

   4:         lifestyle="singleton">

   5:     <interceptors>

   6:         <interceptor>${DumpInterceptor}</interceptor>

   7:     </interceptors>

   8: </component>


  10: <component id="DumpInterceptor"

  11:         service="Castle.Core.Interceptor.IInterceptor, Castle.Core"

  12:         type="TheBasicOfAopWithCastle.Interceptors.DumpInterceptor, TheBasicOfAopWithCastle"

  13:         lifestyle="singleton">

  14: </component>

As you can verify you simply need to register the interceptor as any other component, telling castle that it implement the IInterceptor interface; once one or more interceptors are configured, you can refer to them in the <interceptors> part of other component registration. In the above example I simply registered a concrete implementation for the ISomething class, and I specify that I want to apply the ${DumpInterceptor} registered interceptor to it. Now if you run the following code:

   1: Console.WriteLine("Run 1 - configuration with xml file");

   2: using (WindsorContainer container = new WindsorContainer("castle.config"))

   3: {

   4:     ISomething something = container.Resolve<ISomething>();

   5:     something.DoSomething("");

   6:     Console.WriteLine("Augment 10 returns " + something.Augment(10));

   7: }

You got this output

   1: Run 1 - configuration with xml file

   2: DumpInterceptorCalled on method DoSomething

   3: I'm doing something:

   4: DumpInterceptor returnvalue is NULL

   5: DumpInterceptorCalled on method Augment

   6: DumpInterceptor returnvalue is 12

   7: Augment 10 returns 12

This certifies a couple of interesting things, the first is that every call to the resolved ISomething object is correctly intercepted by the interceptor, the other one is that the interceptor is able to modify the return value. As you can see, the original class implements the Augment methods with a simple addition of the value one to its argument, but passing 10 as parameters returns us the value 12, because the interceptors was able to modify it transparently from the real called method.

The conclusion is that Castle is able to do AOP, even if it don’t support standard concepts, but this is usually not a big problem, you just need to shift a little bit the AOP paradigm to the concept of interceptor.

Clearly the same can be done using fluent interface, here is the code to register an object with an interceptor:

   1: Console.WriteLine("Run 2 - configuration fluent");

   2: using (WindsorContainer container = new WindsorContainer())

   3: {

   4:     container.Register(

   5:         Component.For<IInterceptor>()

   6:         .ImplementedBy<DumpInterceptor>()

   7:         .Named("myinterceptor"));

   8:     container.Register(

   9:         Component.For<ISomething>()

  10:         .ImplementedBy<Something>()

  11:         .Interceptors(InterceptorReference.ForKey("myinterceptor")).Anywhere);

  12:     ISomething something = container.Resolve<ISomething>();

  13:     something.DoSomething("");

  14:     Console.WriteLine("Augment 10 returns " + something.Augment(10));

  15: }

Fluent interface has the Interceptors() method that you can use to list a series of reference to registered interceptors, and you can verify that the output of this snippet is exactly the same of the previous example.