inversion of control

A very handy pattern for large projects. Think of it as an enhancement from the dependency injection pattern.

When using dependency injection, the caller of a class provides the implementations of the requirements.
This gets cumbersome with classes which have a lot of requirements, and large code bases where you may not even know where the implementation is, or how it is called.

Inversion Of Control to the rescue: With this pattern, the framework provides the implementations.

As the implementation is a bit more complex, I’ll only explain the concept:

  • Create a helper, which can construct classes with requirements (non-empty contructor with interfaces)
  • Register the implementations you want to use against the helper at a central place in your code
  • Retrieve all classes which have requirements over this helper

An Example in pseudo-php code:

class IoCContainer extends Singleton
    private $registeredInterfaces = array();
    public function register($interface, $implementation)
        $this->registeredInterfaces[$interface] = $implementation;

    public function construct($object)
        $arguments = get_needed_arguments($object);
        //match each argument with an implementation, and construct the object
        return $instance;

now at the start of your application you register the implementations:

IoCContainer::getInstance()->register("IProgress",new ProgressService());
class Workflow
    public function __construct(IProgress $progressService) { }

    public function doStuff() { }

Now, you do not want to write an IoCContainer yourself. Not because it is hard, but because it has been made before, and tested before. For C# I can recommend the SimpleIoC Container from the MVVMLight Package: MVVM Light (you can get it over NuGet). There are similar implementations for most other languages.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *