Why reflection in dependency injection?

c#, dependency-injection

Solution

Dependency Injection is a design pattern with pretty good language support in most OOP languages. Assuming you're using a statically-typed OOP language, if you define the dependencies a type needs in its constructor, you get compile-time support when you create that type in your Composition Root, i.e. it won't compile if you pass in the wrong types into the constructor.

As an example, take a look at the following program. It composes a `Salutation` class with its dependencies by making use of Constructor Injection. It does so, however, by creating the class structures using the (C#) `new` statement. No reflection is involved. Still, this code snippet demonstrates Dependency Injection:

void Main()
{
    IMessageWriter writer = new ConsoleMessageWriter();
    writer = new SecureMessageWriter(writer, WindowsIdentity.GetCurrent());
    var salutation salutation = new Salutation(writer);

    saluation.Exclaim();
}

TIP: This code snippet is an example from the freely available chapter 1 of DIPP&P.

Your confusion is probably because you think the use of Dependency Injection libraries (that use reflection) is mandatory, but it isn't. I would even argue that when starting with DI, and for small applications, you should start without such library, thus practicing Pure DI, because the help the compiler gives you will be of great benefit. The previous code sample demonstrates Pure DI.

When the application grows, you might want to switch to the use of a DI library, because it can dramatically lower the amount of maintenance on your Composition Root in bigger applications. When doing this, however, you inevitably lose compile-time support. So you should select a DI library that can compensate the loss of compile-time support (some of them contain verification and diagnostic features) and you will need to add some integration tests that allow you to verify the correctness of the configuration to compensate the loss of compile-time support.

Problem

I am learning about Dependency Injection. I understand the basic reason why it is vital when developing large applications. It seems Dependency Injection uses reflection to achieve some of its goals. To me it seems that reflection is a kind of reverse engineering. Why and how is Reflection used and is it optional?

Original source