H is for Harre.

harre.dev

IoC

Getting started with Inversion of Control

Alright, lets dive straight into the deep end! … ok, but not drown in the process of doing so. One step at a time. Lets’s start with an example.

The technical side

Here is some code:

public class Foo
{
    private readonly Bar bar;

    public Foo()
    {
        this.bar = new Bar();
    }
}

To create an instance of Foo we write

Foo theFoo = new Foo();

In this example we have two classes, Foo and Bar. Foo makes use of a Bar to do some work. When a Foo instance is created the creator of the Foo instance has no control over what kind of Bar the Foo instance is going to use. They are stuck together. This code is completely valid but what if we want to let the creator of Foo control the kind of Bar that is used? We have to invert control! Here is the same code with it’s control flow inverted: