Home
Gallery
GuestBook
SourceCode
Contact

Logging using Interceptors in Windsor Container

Posted in Castle Project
This post has been read 716 times

The Windsor container gives you a provision of adding behavior to components without having to change the components implementation. For example if you want to log whenever a method is called through your services class say CustomerService, you can assign an Interceptor for this particular component and add behavior when this component is called. Lets see how logging can be achieved for the CustomerService component.

First thing is to create a LogInterceptor.


    1 public class LogInterceptor : IInterceptor

    2 {

    3     public ILogger Logger;

    4 

    5     public LogInterceptor() { }

    6 

    7     public void Intercept(IInvocation invocation)

    8     {

    9         //Get the method name

   10         string methodName = invocation.GetConcreteMethod().Name;

   11 

   12         Log("Entering method: " + methodName);

   13         invocation.Proceed();

   14         Log("Leaving mehod: " + methodName);

   15     }

   16 

   17     private void Log(string log)

   18     {

   19         Logger.Info(log);

   20     }

   21 }

Here we are implementing the Intercept method of the IInterceptor interface. We are just getting the method name and logging it before the method is invoked and after its completion.

Here is the CustomerService class.

    1 public class CustomerServiceICustomerService

    2 {

    3     CustomerDAO custDAO=new CustomerDAO();

    4 

    5     public CustomerService() { }

    6 

    7     public virtual List<Customer> GetCustomers()

    8     {

    9         return custDAO.RetrieveCustomers();

   10     }

   11 }

The GetCustomers method just calls the DAO object to get a list of customers. Next we define the components in the services.config file so that the Interceptor is injected at runtime.

<configuration>

    <components>

        <component id="LogInterceptor"

              type="Rails.Services.LogInterceptor, Services"

              lifestyle="transient" />

        <component id="service.customer"

               type="Rails.Services.CustomerService, Services"

               service="Rails.Interfaces.ICustomerService, Interfaces">

            <interceptors>

                <interceptor>${LogInterceptor}</interceptor>

            </interceptors>

        </component>

    </components>

</configuration>

Here we are adding a interceptor to the CustomerService class after defining the Interceptor.

Thats that. Now whenever the method is called for this particular component, it is automatically logged.




Name:
E-mail:
Website:
Comment:
 
Anti Bot Image:

Insert Cancel


Subscribe

Random Photo

My Tweets


Top Posts

Source Code

The source code to this site is open-source. You can download the code from here.

Categories


Recent Blogs


Archives


Blogroll