Marc Hughes

I am a developer from a bit west of Boston.

One good reason for IoC

14 Jan 2009

So often I get asked why it's a good idea to use an IoC container and it's always difficult for me to explain.  It's actually a fairly hard question to answer to somebody who has never used one.  I came across one great example this week.

We're working on an educational application made up of a series of lessons.  The general flow of our app is:

  1. Start Up
  2. Login
  3. Request what the next lesson is from the server.
  4. Do the lesson
  5. Send results
  6. Goto #3
To do #3 we have a service object that knows how to make that request to the server and handle the response.


We don't want to have to deal with having a server running all of the time during development of the client.  So we created a brand new class that implements the same interface as that service.  However, instead of asking the server what the next lesson should be, it displays a UI that lets the developer/qa person select a lesson.  With IoC we simply changed the configuration that instantiated that object to use this new class and bamn, it works throughout the application.

Now, I'm working on a demo of the software for management.  We want it to go through a predefined, fixed, list of lessons for the demo.  I created a new service object that maintains a list of lessons to go through sequentially, updated the config, and bamn... our demo is ready.

So now, the exact same application code can be run three different ways depending on what configuration we give it.

Now, it's certainly easy to do a similar thing using other non-IoC approaches.  Maybe you'd need a recompile for those (but is that all that bad?).  The benefit with IoC is that it tends to make developing like this automatic.  It pushes developers to code to interfaces and create modules that can be easily replaced with others.  It's a developer "state of mind" benefit.

In case you're curious, we use Parsley as our IoC container.