harre.dev

Dependency Injection

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:

SignalR dependency injection

My go-to container for IoC at the moment is SimpleInjector because you know.. it’s simple. I’ve used it in a couple of projects and used in a hobby project recently again.

This hobby project uses SignalR for real-time communication between browser and server and after setting that up I wanted to inject dependencies in to the SignalR hubs. It is pretty easy but there was a minor catch. Let’s look at some code.