Home > View Post

Why IoC is different to a Service Factory

I know a lot of people still don't get this and that isn't surprising, it does take a while, but IoC is more than just an object factory... It's advanced dependency injection.

The problem is testability and tight coupling. At a high level, the most common pattern goes something like this

public class Clubs
    private ISpades _spades;

    public Clubs()
        _spades = new Spades;

Now Clubs has a direct dependency on Spades making it difficult to mock Spades when testing Clubs.

It's easy to get around this, we could just have the Clubs constructor specify the Spades dependency.

public Clubs(ISpades spades)
    _spades = spades;

Problem solved. Well maybe, but the reality is that Spades depends on Hearts so we'd have to pass that dependency like so...

public Spades(IHearts hearts)
    _hearts = hearts;

But, continuing the example logically, you'd need to pass hearts into Spades when you construct Clubs! Where does it all end?

Typically at the top of your stack with a class solely responsible for wiring all these dependencies together in the appropriate order that is entirely untestable and, well... yuk!

Make sense?

Some of the freely available IoC containers (such as Castle Windsor) solve all this in a very elegant way.

I've already written about this so why not head off and read our old series on IoC: The Awesome Power of IoC


Josh Post By Josh Twist
1:26 PM
30 Apr 2007

» Next Post: Visiting the Patterns and Practices Team
« Previous Post: Failing unit tests are devaluing your working tests

Comments are closed for this post.

© 2005 - 2022 Josh Twist - All Rights Reserved.