Home > dotnet 4, SOLID > Getting started with Windsor Castle

Getting started with Windsor Castle

Continuing on our quest on the SOLID principle I though I will do a “quick start” tutorial for Windsor Castle as an Inversion of Control Container,as this will touch upon the ‘D‘ i.e.Dependency inversion principle of the SOLID principle.

If you are skeptic about whether to use dependency inversion principle and the IoC Container in your project, just ask yourself these 3 important questions about the design of your application.

1. Is it hard to change because every change affects too many other parts of the system ?
2. When you make a change, unexpected parts of the system break ?
3. Is it hard to reuse your component in another application because it cannot be dismantle from the current application ?

and then think that how best can you solve these problems. If you can solve these problems with improving your design or architecture then you can probably do with out it. Another thing to consider is that how big and complex your system will grow in future.

Before writing the code let’s have a look at some of popular IoC Container.

  • Windsor Castle
  • Structure Map
  • Ninject
  • Unity
  • Spring.NET
  • Autofac

Today I am going to use Windsor Castle as I am more familiar with this container. The code for this sample is going to be the Loan Service project which I posted in the 3 part series of “The Art of Mocking .

First download the latest version of Windsor Castle from here unzip the files and add reference to the two assemblies Castle.Core.dll & Castle.Windsor.dll. This is a significant change from the previous version as in the previous version you had to add 4 assemblies.

Here is the full code for the Load Service which we did a full refactoring and redesigning in “The Art of Mocking” post.

The ICreditHistory interface

using WindsorSample;

namespace WindsorSample
{
public interface ICreditHistoryCheck
{
ICreditResult GetCreditHistory(int socialSecurityNumber);
}
}

The CreditHistory implementation which calls the real webservice

using WindsorSample;

namespace WindsorSample
{
public class CreditHistoryCheck : ICreditHistoryCheck
{
public ICreditResult GetCreditHistory(int socialSecurityNumber)
{
return GlobalCreditServices.GetCreditHistory(socialSecurityNumber);
}
}
}

If you remember we extracted the interface out of the returning result so that we can fake it and here is the interface for that.

public interface ICreditResult
{
CreditRatings Rating { get; set; }
Applicant Customer { get; set; }
int Equity { get; set; }
//{…}
}

And here is the actual CreditResult implementation

public class CreditResult : ICreditResult
{
public CreditRatings Rating { get; set; }

public Applicant Customer { get; set; }

public int Equity { get; set; }
}

And here is the fake credit result class which we use with Mock library to return the desired object.

public class FakeCreditResult : ICreditResult
{
public CreditRatings Rating
{
get { return CreditRatings.VeryBad; }
set { this.Rating = value; }
}

public Applicant Customer
{
get { return new Applicant { Age = 25 }; }
set { this.Customer = value; }
}

public int Equity
{
get { return 90000; }
set { this.Equity = value; }
}
}

And this is the Applicant class whose age we will use to evaluate to approve the loan, I have purposely hide the rest of the property and this is not how one would implement a real life class.

public class Applicant
{
public int Age { get; set; }
// ..Hiding rest of the property
}

Now we will remove the dependency of even the LoanApprovalClass so that Windsor Castle can resolve the class and it’s dependencies.

namespace WindsorSample
{
public interface ILoanApprovalService
{
bool IsQualifiedForLoan(int socialSecurityNumber);
}
}

And now the actual LoanApprovalService class which implements the ILoanApprovalService interface.

public class LoanApprovalService : ILoanApprovalService
{
private ICreditHistoryCheck _iCreditHistoryCheck;

public LoanApprovalService(ICreditHistoryCheck iCreditHistoryCheck)
{
_iCreditHistoryCheck = iCreditHistoryCheck;
}

public bool IsQualifiedForLoan(int socialSecurityNumber)
{
var creditResult = _iCreditHistoryCheck.GetCreditHistory(socialSecurityNumber);

if (creditResult.Rating == CreditRatings.VeryBad)
{
if (creditResult.Customer.Age > 45 &&
creditResult.Equity < 100000)
{
return false;
}
}
return true;
}
}

Phew that’s a lot of code and we are almost there …

Now we will create another class which will hide the complexity of creating a dependency container and all the classes it’s going to inject the dependency for and we are encouraging the single responsibility principle.

public class RegisterDependencyForSystem
{

private readonly IWindsorContainer _container;

public RegisterDependencyForSystem(IWindsorContainer container)
{
_container
= container;
}

public virtual void RegisterLoanServiceComponent()
{
_container.Register(
Component.For<ICreditHistoryCheck>().ImplementedBy<CreditHistoryCheck>().LifeStyle.Transient,
Component.For<ICreditResult>().ImplementedBy<FakeCreditResult>().LifeStyle.Transient,
Component.For<ILoanApprovalService>().ImplementedBy<LoanApprovalService>().LifeStyle.Transient
);
}

public T  Resolve<T>()
{
return _container.Resolve<T>();
}
}

As you can see this class contains IWindsorContainer inteface and through constructor injection we set it’s value.

The “Register” method of this containers takes 2 parameters, first one is interface and the second parameter is the concrete class which implements this interface.

In the first line inside the register parameter we are telling the DependencyRegister class that whenever you see an interface ICreditHistoryCheck return the CreditHistoryCheck. This way we have remove all the hard dependency of all the classes and can inject new classes in the future.

Also notice that I have made the method as virtual so that I can override the method If I want to register a different set of concrete class with minimal code change.

Another way to register dependencies is using a config file but I think maintaining a xml config file for hundreds of classes is going to be much difficult. Moreover I like it using this way is because of the fluent interface it has got. (If you are doing any framework/usable library development I recommend you provide fluent interface to your library.)

And this is the code in Program.cs

public class Program
{
private static void Main()
{

var container = new WindsorContainer();
var registeredComponent = new RegisterDependencyForSystem(container);

registeredComponent.RegisterLoanServiceComponent();

var loanApprovalService = registeredComponent.Resolve<ILoanApprovalService>();
Console.WriteLine(loanApprovalService.IsQualifiedForLoan(123));
Console.ReadLine();
}
}

So I hope this quick start tutorial will give you an insight into the IoC/Dependency Injection and will help you to start using it in your projects.

Advertisements
  1. Yogesh
    August 25, 2010 at 1:34 am

    Windsor Castle looks simple enough. I will try to write some code myself to understand it better.

  2. Eric
    September 13, 2014 at 6:01 pm

    bookmarked!!, I like your blog!

  1. November 22, 2010 at 4:10 am
  2. July 19, 2011 at 9:10 pm

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: