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:
- Start Up
- Request what the next lesson is from the server.
- Do the lesson
- Send results
- Goto #3
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.