Archive
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.
Mocking Routes
I have a done a couple of post on how good TDD is and the use of Moq framework and today I am sharing some code to put all these ideas into practice with a real life project.
I have been working in ASP.NET MVC for sometime and this is one area where I first started using Moq and TDD i.e. testing ASP.NET MVC routes. This unit test project is part of the SparkViewEngine post i did some time ago and goes on to show good the MVC architecture is.
The first and foremost thing is to follow the triple “A” principle for writing unit test i.e.
- Arrange
- Act
- Assert
Lets write some code to Mock the HttpContextBase in order to simulate an Http web request and then we are going to test our routes to verify that it maps to our controllers properly.

As part of the “Arrange” we will create a RouteCollection object and pass it to RegisterRoutes method of the application class. This is the class which inherits from HttpApplication class and gets created in your Global.asax.cs file when you create a new MVC application.

In the next test we will test that our routes for a detail view. This is where the whole principle of “Separation of Concerns” really shines, we are able to test our routes with hosting on web server, without creating any web page or server pages etc.

If you notice carefully you can see how I have named these test and have a lot of resemblence with Behaviour Driven Development (BDD) as I am a huge fan of BDD too.

If your arrange your test view as shown above you will see the highlighted line is really good in terms of readability. Just follow the pattern like
For {Namespace} when {Class Name} the result expected is {Test Name}
You will see it reads like “For SparkViewEngineTest when TestingRoutes the result expected is This_goes_to_Person_Index_action” .
The whole sentence makes a lot of sense and is quite helpful when working on large projects with lots of unit test. (Another nice pattern to follow for your projects)
And when we run our unit tests we can verify our results.
LinqPad
I know you guys have already heard a lot about LinqPad and how great it is. If not here is a blog about LinqPad and it’s a great tool for learning LINQ.
But one of the cool things about LinqPad is that it is a great code snippet IDE too , with LinqPad you will never ever have a need to write a Console Application for a quick prototype.
Today I am going to show how to use external assembly or custom assemblies to use in this code snippet IDE. For illustration sake I’m going to use the JavascriptSerializer class to see whether my dotnet class will get serialize or not as a JSON Object and if it serializes then how would my JSON object will look like
So let’s assume you have downloaded and install LinqPad successfully. In order to add an external assembly click Query > Query Properties > Additional References.

Click on “Add” to add a new assembly.

You can type in the assembly you want to add and Autocompletion will take care of it.

Import any additional namespace you might have with in the selected assembly. Like in my case I am importing the System.Web.Script.Serialization namespace.

Lets write some code…

This is one gotchas I want to highlight when you first start using LinqPad. When you hit the run button you see it says “Error compling query” and it took me a while to figure it out. It’s complaining becasue in LinqPad by default it assumes you are trying to execute some expression so lets change it to “C# program”.

Now when we run the program it shows the desired result.

JQuery Snippets
If you are web developer or thinking into moving to the lighter side (with a pun
) then you simply can’t ignore JQuery and in my personal opinion invest some time and energy into it and it will pay you off in the long run.
A couple of weeks ago I blogged about the free JQuery ebook and I also blogged about how to roll out your own code snippet using the code snippet designer.
This post is about the jQuery snippets which I think is a great way of learning jQuery syntax. You can download it from here. Once it’s downloaded unzip the file, run the msi and complete the installation.
Before we start using the snippets lets browse to the “Documents\Visual Studio 2010\Code Snippets\Visual Web Developer” folder and as you can see there are two folders “My HTML Snippet” and “My JScript Snippets”.
Under “HTML Snippets” folder

Under JScript Snippets” folder

If you open one of these snippet files you can see it is quite similar to what we did using the snippet designer and shows the full potential of using snippets in your own development environment.
Lets start using the snippets and get some jquery code in our page. Below is a simple html page and when we type the keyword “jq”

and when we hit tab twice the snippet generates the base jquery code, it’s that simple.

Now it’s not too scary to get use to of jQuery syntax .
The Art of Mocking – Part 3
Before completing the trilogy let’s have a quick recap on what we have done so far.
The Art of Mocking – Part 1
The Art of Mocking – Part 2
One of the biggest gotchas for mocking framework is that you can’t mock a sealed class and can only mock either an interface or an abstract class. If you every try doing it to a sealed class you get this exception.
Type to mock must be an interface or an abstract or non-sealed class.
We learned in the previous posts how we can design our classes using SOLID and TDD principle so that you can use mocking framework to test it in isolation, but how about a piece of code which has a dependency on an existing .NET framework class which is sealed or doesn’t provide an interface or an abstract. How would you approach mocking with that.
For example we had a lot of problems when we were using LinqToSql as it’s DataContext class does not provides and interface and the System.Data.Linq.Table class is a sealed class and the work arounds were not that great.

It’s an interesting problem and this is where an interesting framework comes into picture and it’s called Moles Framework. Moles is part of the Microsoft pex and moles research project, it can be downloaded from visual studio gallery but for PEX you need a MSDN subscription.
I haven’t played with it yet but through the documentation I could see what its potential is, and if I come across something which I can’t mockup I will use it rather extracting interfaces and working on workarounds.
The Art of Mocking – Part 2
We are back with part 2 of the series, if you haven’t read the first part of the series I recommend please read it in order to see what changes we are going to make to our classes.
First lets start decoupling the CreditHistoryCheck class which calls the public GlobalCreditServices and extract the interface out of this class.

Lets rewrite the CreditHistoryCheck class using the ICreditHistoryCheck interface

Now due to the interface (contract) it is easy to decouple the dependency between the LoanApprovalService class and the CreditHistoryCheck class using constructor injection.

As you can see the LoanApprovalService class depends on the interface and not the concrete class.
Lets apply the same principle to seperate the return resultset (data) from the actual result set so that we can create fake objects and use it in our test.

As you can see above we seperated the attributes of CreditResult class into an interface and created a fake object alongside the concrete class.This is where things gets very interesting and the whole concept/debate of fake vs mock objects comes into the developer community.
Now lets write the unit test using the Moq framework and I will explain it to you line by line.( Of course add reference to Moq.dll first
)

So in the first line of code we are creating an instance of FakeCreditResult so that when we new up this object we can assert different set of attribute, it’s like we are forcing our fake object to give us a desired result with out modifying our actual object i.e. CreditResult. ( almost the ‘O’ open/close principle of SOLID)
Next line is interesting and the most important of all, this is the first time we are refering to the Moq framework. What it means that we are asking Moq framework to new it’s Mock Object and it takes a generic type of either an interface or abstract class.So we are asking Mock class to return an instance of mock object which is of type ICreditHistory.
In the next line we setup the mock object using the Setup method and use the lamda expression and the expression x=>x.GetCreditHistory means when ever we refer to the mock object just fakely execute the GetCreditHistory method.Also worth notice is that the method signature of the interface ICreditHistory takes an int (social security number) and we are saying :-
It.IsAny<Int32>()
So what we are saying with this that I don’t care what numeric value you (the ‘Moq’ framework) substitute just simulate to execute the method but after the execution return my fake object i.e. mockCreditResult object.
So in all we created a Mock object ‘mockCreditHistory‘ which holds an internal object and implements the ICreditHistory and when we refer to this internal object it’s GetCreditHistory method will be executed.
Now we can pass this internal object using the mockCreditHistory.Object property to the LoadApprovalService as you remember we decouple the dependency between the 2 class and use constructor injection to pass the ICreditHistoryCheck to the LoanApprovalService.
In the next line we called the service.IsQualifiedForLoan method with a fake parameterand now when we run the test the Asset.IsTrue will return true as the result will always be true.
And this is how the FakeCreditResult class looks like, remember it is just for illustration and not the best way of creating DTOs there are lot of details I have removed from the object for the sake of clarity ( for example no Id’s etc)

And this is final dependency diagram looks like after full refactoring and using SOLID design principles

As you can I have used both fake objects and mock objects and illustrated how to use each of these approaches and due to the mock object I am not running this test against the actual web service.
Sometimes it’s easy to ignore such finer details but as your projects goes bigger and complex everday you will see the benefit of using such design principles and patterns. Remember what ever I have stated is nothing new it is still good old object oriented design.
Feel free to write comments and please let me know if I need to work on Part 3 as well …