Home > Design Patterns, dotnet 4, SOLID > Why program against an interface ?

Why program against an interface ?

I have done a lot of post regarding interface based programming and we have seen some good benefits of programming against an interface as compare to its concrete implementation. One of the best things it does it that it promotes SOLID design principles and allows us to have a level of abstraction or separation of concerns.

If you haven’t read my previous post about the benefits of interface I recommend reading them and here are some of those posts.

In this post I am going to show another benefit of using interfaces and that is how easy it is to add additional behavior (decorators) without changing the code. With interfaces you are able to provide nice extensibility point and keeping our code SOLID ( yes it is the big ‘O‘ in SOLID) and as usual Dependency Injection plays a key role in accomplishing the task with minimal effort.

Let’s start with a simple interface like this one.


public interface ICustomerRepository
   List<Customer> GetCustomers();

And let’s write the CustomerRepository class which implements this interface.

public class CustomerRepository : ICustomerRepository
   public List<Customer> GetCustomers()
      return new List<Customer>
                   new Customer(1, "Joe", "Blogg"),
                   new Customer(2, "John", "Doe")

And this is our client code that calls the CustomerRepository class, it’s a standard example I have used in most of my posts depicting a real world example of business layer calling the repository layer.


public class CustomerBl : ICustomerBl
   private readonly ICustomerRepository _customerRepository;
   public CustomerBl(ICustomerRepository customerRepository)
      _customerRepository = customerRepository;

   public List<Customer> GetCustomers()
      return _customerRepository.GetCustomers();

I will add a simple class diagram for people who love to see the class diagram,as I personally favor class diagram over code.

Customer Repository Injected into Customer Business Layer

As you can see nothing special, we are just using constructor injection in our CustomerBl so that through IoC I can decide which class will be injected into the CustomerBl as long as the class implements the ICustomerRepository interface (contract).

So far so good the code is running fine and it’s in production, your customer is happy and you feel good about it.

After some time the customer says that I want to do logging when this function is called and the first thing which comes to your mind is okay I will write a logging code in the CustomerRepository GetCustomers() method.

But wait lets put some thought into this. First as soon as you are modifying the CustomerRepository class you are breaking the Single Responsibility Principle as this class has now 2 reasons to change.

  • If the GetCustomers() method logic changes
  • If the logging mechanism changes

Lets think “does this logging really the CustomerRepository’s responsibility” and at the same time we don’t want to put the logging code into CustomerBl class as it’s not even its responsibility. And what about the logging it could change in the future.

So let’s abstract the logging responsibility into its own interface like this.


public interface ILogger
   void Log(string message);

And the class which implements this interface is


public class DebugLogger : ILogger
   public void Log(string message)

Here I have chosen a simple class which writes to the output window to keep the example as simple as possible and since we are implementing through interface we can easily change it into file based or database based logger using the Dependency Injection Principle.

Here is the interesting part as you can see from our ICustomerRepository interface that the CustomerBl class just care for this interface and has no knowledge of what the actual class does.

This gives us a good opportunity to implement a new class which has the same interface signature but does the logging and then calls our actual CustomerRepository class as is. With this philosophy nothing has changed and the new class would act as a proxy.

Hmmm let me show you the code and see if I can make more sense so I will create a new class called LogCustomerRepository which will implement the ICustomerRepository interface and will have dependency on it as well as on the ILogger interface.


public class LogCustomerRepository : ICustomerRepository
   private readonly ICustomerRepository _customerRepository;
   private readonly ILogger _logger;
  public LogCustomerRepository(ICustomerRepository customerRepository,
         ILogger logger)
      _customerRepository = customerRepository;
      _logger = logger;

   public List<Customer> GetCustomers()
      _logger.Log("Before the get customer method");
      var result = _customerRepository.GetCustomers();
      _logger.Log(string.Format("Total results found {0}", result.Count));
      return result;

And an elaborated class diagram.

Log Customer Repository Injected into Customer Business Layer

Customer Repository Injected into Log Customer Repository
So as you can this class just decorates the CustomerRepository and it shouldn’t make any difference to the client code(CustomerBl) as both the class implement the same interface (contract).

Now only thing left is wire this up in our IoC and I am going to use Castle Windsor Installer to have a nice separation of the configuration from the actual container.

If you are not familiar with Castle Windsor installer class please read my previous post about it.


public class CustomerInstaller : IWindsorInstaller
   public void Install(IWindsorContainer container,
                       IConfigurationStore store)




This is the core of how registration and components works in Castle Windsor. The important thing to notice here is I am using named component registration as I want to make sure that when my CustomerBl class asks CastleWindsor to resolve for an implementation of type of ICustomerRepository it will return the LogCustomerRepository class instead of CustomerRepository and this way I am making sure that the decorators are invoked in the right order.

So in the ServiceOverrides method I am telling CastleWindsor that CustomerBl has a Dependency on ICustomerRepository and the name of the variable which is passed into the constructor is “customerRepository” and when you come across this variable then invoked the registered component which has been tagged as “LogCustomerRepository” rather than the default registered component CustomerRepository.

Although this syntax is very specific to Castle Windsor but the concept is quite uniform across all the IoC containers.

Let’s write a unit test to see how this all comes together.


public class When_using_CustomerBl
   private IWindsorContainer _container;
   public void Setup()
      _container = new WindsorContainer();
      _container.Install(new CustomerInstaller());

   public void Should_be_able_to_get_customers()
      var customerBl = _container

      var result = customerBl.GetCustomers();
      Assert.IsTrue(result.Count > 0);

And when I run the test it passes with the desired result and in the output window I do see the messages I expect.

Unit Test

As you can see from the Watch window that how these interfaces are resolved by Castle Windsor and how I am getting the correct type when I need it.

This way of decorating interfaces and creating decorators is a nice and easy pattern but it also gives us some insight into Aspect Oriented Programming as these decorators are merely cross cutting aspects.

For example we can easily create Logging,Security,Caching,Instrumentation etc decorators and Inject them with Castle Windsor.

  1. July 21, 2011 at 11:03 am

    Great job. And so timely for me to read a post like this from a great mate like you. Keep going!!

  2. July 30, 2011 at 5:34 am

    Hi Yogesh,
    Thanks a lot buddy, great to see such encouragement and appreciation. I have been very busy last couple of weeks and didn’t get time to check your comment.

  3. sasireka
    August 12, 2011 at 6:35 am

    Hi Prashant,

    Its really useful to me. Thank you so much. I have one doubt. In this example, you are using castle windsor. I am new to castle windsor and now i am learning the castle windsor so could you please tell me what is advantage for using castle windsor rather than using normal code (oops).

    • August 12, 2011 at 10:36 pm

      Hi Sasireka,
      Thanks and i am glad that you are finding my post useful. The advantage of using castle windsor as my Dependency Injection container is that the creation of components and it’s dependency are being resolved by the IoC container. That means I don’t have any hard coded newing up of objects, this gives flexibility as I can change these dependencies remember it is the ‘D’ in SOLID programming. If you follow all my previous articles like “The Art of mocking” and “Building Loosely Coupled Architecture” and then you will know what i mean.

  4. August 26, 2011 at 2:38 am

    Gr8 post Prashantbhai. I have been using Unity as IoC container (only at top level and not that deep as need never existed). Not sure if it’s possible or not, but what if I want to switch over between LogCR and normal CR during runtime. That is imagine if a settings page for the application has “Log Customer = checkbox” and after saving it, can we somehow switch the component? Need never existed, so haven’t tried out the proof of concept, but while reading your post, this scenario clicked me!! I imagine in web application, we do need to restart the application in that scenario, will it apply for all users? and so many other doubts. Would be a good thing to try out 🙂

  5. August 31, 2011 at 10:23 am

    Gr8 post as always.
    Love this blog and keep the good work 🙂


    • September 20, 2011 at 8:26 pm

      Thnx betonlolAlek,
      It’s comment like yours keep me going and I hope I’ll be able to being more interesting and good posts in the future.

  6. sri
    August 20, 2013 at 7:29 pm

    Prashanth, Wow. simple words.. simple example .But 100% quality concept. Wow your very good at presenting. I understood your concepts .We really like your posts

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: