IoC container, check for errors at compile time

What I'd like to know is, if Unit Tests were - for any reason - not possible, and thus IoC could not be tested at compiled time, would this prevent you from using an IoC container and opting for direct instantiation all over your code?

You present a false choice here: either use a container, or else "direct instantiation all over your code". But you can actually still practice dependency injection without any container. Instead of doing this:

public void Main(string[] args)
{
    var container = new Container();
    // ... register various types here...

    // only Resolve call in entire application
    var program = container.Resolve<Program>(); 

    program.Run();
}

You just do this:

public void Main(string[] args)
{
    var c = new C();
    var b = new B(c);
    var a = new A(b);
    var program = new Program(a);
    program.Run();
}

You can still get all of the advantages of dependency injection this way: the components don't create each other and can remain highly decoupled. Construction of components remains the responsibility of the application composition root, even though no container is used there. You also get the compile time check that you seek.

Two more remarks:

  1. you tagged your question dependency-injection, so I'm assuming you're indeed using dependency injection as opposed to the Service Locator pattern. In other words, I'm assuming that you are not exposing and invoking the container throughout your code, which is not necessary and not recommended. My answer doesn't work any more if you do Service Locator. Please count it as a strike against Service Locator, not against my answer. Constructor injection is a better choice.

  2. programmers will typically chose to use a container instead of this manual approach, because in a large application it can get non-trivial to keep the order of instantiations correct - a lot of reordering might be required simply because you introduce a single new dependency somewhere. Containers also offer additional features which make life easier.


You can't test all of your code with a compiler at build time. It sounds absurd. You must write different kind of tests anyway. And container's configuration is a good candidate for Integration Testing. You can configure your tests to run automatically as a post-build event, but this can increase build time. In any case it's a bad reason to decline IoC container usage.


I've written a compile time IOC container using roslyn SourceGenerators, and it does indeed provide compile time warnings and errors if you make a mistake.

Of course there are occasions where something can only be provided at runtime, but there are ways to do that explicitly, meaning we can still give you errors if dependencies are missing.

Check it out at https://github.com/YairHalberstadt/stronginject


It is impossible for the compiler to validate the working of your whole program. The fact that your program compiles, doesn't mean it works correctly (even without using IoC). For that you'll need both automated tests and manual testing. This doesn't mean that you shouldn't try to let the compiler do as much as it can, but staying away from IoC for that reason is bad, since IoC is meant to keep your application flexible, testable and maintainable. Without IoC you won't be able to test your code properly, and without any automated tests it is almost impossible to write any reasonably sized maintainable software.

Having the flexibility as IoC provides however, does mean that the dependencies some particular piece of code has, can't be validated anymore by the compiler. So you need to do this in another way.

Some DI frameworks allow you to verify the container for correctness. Simple Injector for instance, contains a Verify() method, that will simply iterate over all registrations and resolve an instance for each registration. By calling this method (or using a similar approach) during application startup, you will find out during (developer) testing if something is wrong with the DI configuration and it will prevent the application from starting. You could even do this in a unit test.

Important however is, that testing the DI configuration should not need much maintenance. If you must add a unit test for each type that you register to verify the container, you will fail, simply because the missing registration (and thus a missing unit test) will be the reason to fail in the first place.

This gives you 'almost' compile-time support. However, you need to be conscious about the design of your application and the way you wire things together. Here are some tips:

  1. Stay away from implicit property injection, where the container is allowed to skip injecting the property if it can't find a registered dependency. This will disallow your application to fail fast and will result in NullReferenceExceptions later on. Explicit property injection, where you force the container to inject a property is fine, however, use constructor injection whenever possible.
  2. Register all root objects explicitly if possible. For instance, register all ASP.NET MVC Controller instances explicitly in the container. This way the container can check the complete dependency graph starting from the root objects. You should register all root objects in an automated fashion, for instance by using reflection to find all root types. The MVC3 Integration NuGet Package of the Simple Injector for instance, contains a RegisterMvcControllers extension method that will do this for you. Integration packages of other containers contain similar features.
  3. If registering root objects is not possible or feasible, test the creation of each root object manually during startup. With ASP.NET Web Form Page classes for instance, you will probably call the container from within their constructor (since Page classes must unfortunately have a default constructor). The key here again is finding them all in once using reflection. By finding all Page classes using reflection and instantiating them, you'll find out (during app start-up or test time) whether there is a problem with your DI configuration or not.
  4. Let all services that your IoC container manages for you have a single public constructor. Multiple constructors result in ambiguity and can break your application in unpredictable ways. Having multiple constructors is an anti-pattern.
  5. There are scenarios where some dependencies can not yet be created during application start-up. To ensure that the application can be started normally and the rest of the DI configuration can still be validated, abstract those dependencies behind a proxy or abstract factory.