Yet another geek blog about software development

Main menu

Tag Archives: Design Patterns

I decided to write this post after reading a question on StackOverflow, where the OP was asking for recommendations to simplify his IoC setup code – to make it more readable and also to prevent runtime errors when resolving instances, whenever a change is made.

I feel his pain. Anyone that used and configured an IoC container such as Unity knows how easy it is to break things when you add or change an existing configuration. So, how to detect if things are broken until it’s too late (runtime errors)? Writing tests, obviously.

In this post I’ll show you a quick and simple way to test your dependencies using Unity IoC container.

The scenario – a shopping cart service

Let’s assume a simple scenario – a service that allows users to check the all the items and corresponding prices of his shopping cart. The service uses a logger, a repository to read the information of the cart and a currency service that is used to display the prices in the currency selected by the user:

The constructor takes 2 optional parameters (appSettings and connectionStrings), which can be used for testing purposes. If no values are provided it will use the values from the configuration file.

AsyncLogger, ConsoleLogger and FileLogger are registered as named instances

ICurrencyApiClient and IRepository are registered using a factory method

Configuring the unit tests

Now it’s time to write the unit tests. Instead of manually adding tests for every single dependency, we can use the Registrations property of IUnityContainer to get the metadata of all registered dependencies:

It’s just as simple as that. Given the registered type and the instance name of the dependencies, I can try to resolve them. If the instance is null or an exception is thrown the test will fail, which means that there is something wrong with our Bootstrapper. Also, I check if the returned instance has the expected type.

Running the code using Reshaper:

Some tests failed because I forgot to add a configuration file with the settings used by both the CurrencyApiClient and Repository. Test for IShoppingCartService fails as well because it uses both dependencies.

Fixing the code and running the tests:

All good now. As you can see, there is a test for every single type/instance name.

Final thoughts

You should add as many unit tests as possible to your code – IoC setup is no exception. Also, these tests do not exclude the usage of other type of tests such as integration or smoke tests.

My article is a good starting point, but this might not be enough. For example, if you have ASP.NET MVC or ASP.NET Web API applications, you should test your DependencyResolver in order to ensure that all controllers are being instantiated correctly (i.e. without throwing exceptions).

Consider also running these tests for every single environment – each environment has its own configuration, so better be safe than sorry 😉

As you can see, for each model you have an if statement. This works fine if you only need to create 2 or 3 validators but if you need more your code will get bigger and bigger and will be harder to read/maintain. The same applies to switch statements.

The first step to solve this problem is to create a Dictionary to store the validators. The key of the Dictionary will be the type of the model and the value will be a delegate that creates an instance of the validator for that model:

Composing specifications

Existing specifications can be combined to form more complex ones. Using these extension methods it’s easy to create composite specifications (see this article to understand how to combine lambda expressions):

Using T4 to generate Specification Objects

T4 is a code generator built right into Visual Studio. You can generate any text file using T4 templates: C#, javascript, HTML, XML and many others. If you’ve never heard about it, this is a good place to start:

I’ve created a T4 template that generates automatically all the Specification Objects, one for each entity in our model. All the generated objects have all the public properties of their respective entities, including association properties. All objects were marked with the [Serializable] attribute, so you can easily serialize it if you need.

In a previous article I’ve created query objects for Entity Framework, I’m generating exactly the same properties in this template. You can see a complete description of the generated properties here.

When you save the template file or you rebuild the project the code will be regenerated. If you don’t want to generate the code, remove the value of the Custom Tool property in the property browser of the template file (by default the value is TextTemplatingFileGenerator).

I’ve read some stuff about T4 templates in the last 2-3 years, but only recently I decided to give it a try. My first attempt was to generate Query Objects for Entity Framework, that’s what I’ll talk about in this article – what’s their purpose and how to use them.

In part 2 I’ll create a demo ASP.NET MVC application that uses query objects created with this template. I already have another T4 template that creates javascript objects for my entities, and I’m developing a custom ASP.NET view template for those objects.

What is a Query Object?

A Query Object is an interpreter [Gang of Four], that is, a structure of objects that can form itself into a SQL query. You can create this query by referring to classes and fields rather than tables and columns. In this way those who write the queries can do so independently of the database schema and changes to the schema can be localized in a single place.