Tuesday, 19 April 2011

Don’t use ConfigurationManager!

.Net is generally has a nice API but something's are problematic when the classes are static, like FormsAuthentication or ConfigurationManager, allowing developers to use them anywhere in the code.

If you’re one of those dev’s that slaps a ConfigurationManager.AppSettings in the middle of a class then stop, please just stop.  I know that it works but the side effect is that you’re creating a hidden dependency that dev’s who come along afterwards to maintain the code know nothing about and then get bitten in the ass when they try to change something (yes I know you should look through the code for things like this but I was in a hurry ok?)

To be clear, I believe that settings should be injected into classes that need them rather than having to provide a whole object to handle it (think of a connection string) but if you're refactoring old code and already have the dependency then its good to be able to start off by being able to see the dependency rather than have it hidden.

I know what you’re going to say “but its a static class so I don’t have any other way to use it”, but that’s where you’re wrong and with a little work you can have dependency injected, unit tested code loveliness and in fact I’ve done the work for you all you have to do is reuse it!

So what’ve I done? Well quite simply just written a wrapper around the ConfigurationManager’s static methods that allow you to use it via an interface and inject it into any classes that may need it, lets look at some code to see it a little clearer.

Here we have an absurdly simple example that demonstrates that just looking at the public interface of this class you’d have absolutely no idea that it uses ConfigurationManager internally:
   1: public class SomeClass
   2: {
   3:     public void SomeMethod()
   4:     {
   5:         int value = int.Parse(ConfigurationManager.AppSettings["TheValue"]);
   6:     }
   7: }

At least with the code above you may go investigating “what lies beneath” and find the hidden dependency but what if you came across this:

image

My guess is like me you’d anticipate that the class had been sorted for dependency injection and only needed the 2 dependencies that its constructor was advertising and it wasn’t until you got bitten by a problem that you’d look at the code and find:


   1: public class SomeClass
   2: {
   3:     private readonly IDependency1 _firstDependency;
   4:     private readonly IDependency2 _secondDependency;
   5:  
   6:     public public SomeClass(IDependency1 firstDependency, IDependency2 secondDependency)
   7:     {
   8:         _firstDependency = firstDependency;
   9:         _secondDependency = secondDependency;
  10:     }
  11:  
  12:     public void SomeMethod()
  13:     {
  14:         string theSetting = ConfigurationManager.AppSettings["TheValue"];
  15:  
  16:         theSetting = theSetting + "ArbitaryValue";
  17:  
  18:         _secondDependency.TheSetting = theSetting;
  19:  
  20:     }
  21: }


So the solution to both of these problems is to inject the ConfigurationManager into the clas and to do enable us to do that step forward IConfigurationManager.

The code is written in .Net 4.0 but should work with .Net 2.0 and above if recompiled to target whatever version of the framework you are working with.  For brevities sake I’m just going to show the second code snippet using IConfigurationManager which makes the code look like this;


   1: public class SomeClass
   2:    {
   3:        private readonly IConfigurationManager _configurationManager;
   4:        ..... 
   5:  
   6:        public SomeClass(IConfigurationManager configurationManager, IDependency1 firstDependency, 
   7:                         IDependency2 secondDependency)
   8:        {....}
   9:  
  10:        public void SomeMethod()
  11:        {
  12:            string theSetting = _configurationManager.AppSettings["TheValue"];
  13:  
  14:            theSetting = theSetting + "ArbitaryValue";
  15:  
  16:            _secondDependency.TheSetting = theSetting;
  17:  
  18:        }
  19:    }


Now anybody looking at the public interface for this class can see that it has a dependency on IConfigurationManager which in turn should indicate that the code is going to be reading from a App or Web.config. The only difference to the actual code using the configuration setting is the use of the instance variable rather than the static class.

The actual IConfigurationManager project contains the implementations of both ConfigurationManager and WebConfigurationManager (plus tests) to show that you can use IConfigurationManager to replace either of these classes. Currently only the more common methods & properties have been implemented as following the principle of YAGNI I’ve not bothered adding methods such as OpenExeConfiguration that I don’t need at the moment.

The one extra thing that I have added is the ability to be able to return a strongly typed custom configuration section rather than retrieving a section as an object and then casting it, so instead of :


   1: var sect = ConfigurationManager.GetSection("sampleSection")as SampleSectionProvider;

You can do:

   1: var sect = _configurationManager.GetSection<SampleSectionProvider>("sampleSection");


I know there’s not a lot of difference but I prefer the generic version since an error will be thrown if it can’t get the appropriate section handler that’s been specified.

One word of warning the Core project has a dependency on System.Web this isn’t a problem for me as I’m mostly using this with web projects but if you wanted to use this with a desktop app you will need to either remove the class from the project or except the assembly dependency.

If you are using ConfigurationManager then I strongly recommend trying out IConfigurationManager, if not for you then for the person who has to maintain the code in a few months time Winking smile

Tuesday, 12 April 2011

Up and coming presentations

Conferences

I’ve been lucky enough to have presentations voted for in both the upcoming DDD Scotland and DDD South West.

The “Is your code S.O.L.I.D?” presentation is heading north of the border to Glasgow on the 7th May for DDD Scotland, registration took place on 1st March so hopefully if you wanted to come you’re all sorted, otherwise commiserations.

June will see me back in Bristol giving a new presentation “Kanban? what is it and how can it help?”, registration for DDD South West opens today at 10am so be sure to be standing by your browsers and ready to register if you want to attend.

User Groups

As well as presenting at the conferences mentioned I will also be taking my “Is your code S.O.L.I.D?” presentation on the road, firstly to .Net Developers Network in Bristol tonight and then to NxtGen Shenfield on 26th April.

Hopefully I’ll see you at one of these events, please feel free to grab me for a chat and if you’d like me to present at your user group then drop me a line Smile

Monday, 4 April 2011

Book Review: Dependency Injection in .Net

So Manning Books have been were kind to me again and have let me have another book to review namely  Dependency Injection in .Net by Mark Seeman.

Before I got this book I thought that I had a fairly good understanding of what Dependency Injection (DI) was all about but when I opened the book and found out there were 500+ pages I thought that I obviously didn’t know a lot!

When you take a closer look at the contents you find that its split into 4 parts:

  • Introduction
  • DI Catalog
  • DIY DI
  • DI Containers

The book is structured so that a complete newcomer to DI could read the book cover to cover and learn all about it or if you already have experience you can jump to the parts that you don’t know about or your knowledge isn’t that in depth.

Introduction

The introduction is a little more than it sounds as it comprises 3 chapters starting with introducing DI itself before moving on to  DI fundamentals and DI containers.

These 3 chapters give anybody who doesn’t know anything about DI a through grounding in what DI is, how DI works and what DI containers are for and how to use them.

You will also be introduced in these chapters to 2 themes that run throughout the book, the first being how to create a sauce béarnaise and how it has similarities with DI, and the second is Mary Rowan a developer who is creating an application and we can see how DI helps in that process.

DI Catalog

This section introduces you to a lot of the theory around DI listing patterns and anti-patterns and it covers how to refactor code to be able to use DI.

The chapters on patterns & anti-patterns give you the name and details of each and are backed up with code examples so you can see how each is implemented, and in the case of anti-patterns what you can do to alleviate the problem.

The third chapter is devoted to refactoring existing code towards DI and covers a load of scenarios such as cyclic dependencies and constructor over injection to name two.

DIY DI

This section details how you can implement DI yourself, otherwise known as “poor mans DI”, and runs through the 3 key concepts: Object Composition, Object Lifetime and Interception.

Each concept has a chapter devoted to it with Mark explaining the concept and then showing how you can code it yourself increasing the complexity of the code as each chapter progresses.

The chapter on Object Composition in particular shows you how it works with various technologies such as console applications, Asp.Net MVC, Asp.Net Webforms, etc.

DI Containers

The final section of the book takes you through some of the more well known DI Containers and how they satisfy the concepts laid out in the previous section.

This section differs from the others in that it has 6 chapters rather than 3 with each DI container having its own chapter, the containers currently covered are:

  • Castle Windsor
  • StructureMAP
  • Spring. NET
  • Autofac
  • Unity
  • MEF

Summary

This book provides everything you need to know about DI ranging from what it is, through patterns for implementing and key concepts, to covering various DI containers that are available today and whilst the book is aimed at the .Net world I believe that it would be useful to any developer that wants to implement DI it whatever language they use.

This isn’t just a theoretical book as every step of the way demonstrates each subject covered with code examples so that you can see how you actually use the subject in question rather than having to try and work it out for yourself, yes the code is ‘demo’ code but you can easily see how you actually implement what is being discussed.

The only niggle I have is that the DI Container Ninject isn’t covered in the book, this was specifically mentioned in the MEAP forums for the book and Mark said the reason for this was he was unaware of it until after he had completed the DI containers section and it was too late to add further content. A poster on the forum suggested Mark could create a separate downloadable chapter on it to which Mark said it sounded like a good idea.

This book is not due to be published until July but is available now through the Manning Early Access Program (MEAP) and Mark has said that the content is now basically complete and the remaining changes are likely to be typographical. 

Many thanks to Manning Books and Mark Seeman for the opportunity to review this book.