9.3. Inversion of Control

Another way to deal with dependencies is to use what is known as inversion of control (IoC). Inversion of control means that rather than code creating its dependencies before calling them, those dependencies are created at the top and pushed down.

For example, rather than having code that requires a logger, create that logger, as in this example:

public class LessDependent
{
    public static readonly ILogger log = new MyLogger();

    public int Add(int op1, int op2)
    {
        int result = op1 + op2;

        log.Debug(string.Format("Adding {0} + {1} = {2}", op1, op2, result));

        return result;
    }
}

The logger is created someplace above the LessDependent class and pushed down into it via its constructor as shown here:

public class LessDependent
{
    private ILogger log;

    public LessDependent(ILogger log)
    {
        this.log = log;
    }

    public int Add(int op1, int op2)
    {
        int result = op1 + op2;

        log.Debug(string.Format("Adding {0} + {1} = {2}", op1, op2, result));

        return result;
    }
}

It is then incumbent on the code calling this class to create the right dependencies and pass them down, as in the DoAddition method here:

public class Top
{
    public void DoAddition()
    {
        ILogger log = new MyLogger();
        LessDependent less = new LessDependent(log);
        int result = less.Add(1, 2);
    }
}

Although this is a simple example, it demonstrates the principle. Just as with a factory class, the calling code has no idea how the dependencies were constructed or anything about the implementation classes themselves.

As with a ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.