14

I have a simple question.

Let's say I have a .Net solution, with different projects like some class libraries (bll, dal, etc) and a main project which can be a web application or a wpf application, it doesn't matter.

Now let's say I want to use an IoC container (like Windsor, Ninject, Unity, etc) to resolve stuff like validators, repositories, common interface implementations and such.

I put it all together. Compiles and runs fine. Then, someday, I add a new service, and in my code I just try to resolve it through the IoC container. Thing is, I forget to register it in the IoC configuration.

Everything compiles, and the application gets deployed and runs. All works fine, except for when a page's code asks for that new service to the container, and the container answers "hey, I don't know anything about this service".

You get your error logged, and the user friendly error page. You'll go check the error, see the problem and fix it. Pretty standard.

Now let's say we want to improve the process, and in some way be able to know at compile time if every service that we expect the IoC container to handle is registered correctly in the code.

How could this be achieved? One thing, Unit Tests are ruled out from possible answers, I'm looking for another way, if it does exist.

Thoughts?

EDIT - After some answers and comments, it seems that Unit Tests are indeed the only way to achieve this feature.

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? I mean, would you consider too unsafe and risky to use IoC and late binding, and see its advantages being outscored by this "flaw"?

Matteo Mosca
  • 7,380
  • 4
  • 44
  • 80
  • 2
    As @Chriseyre2000 pointed out in his answer, Unit Testing is a very effective way of checking the IoC configuration, so you might reassess you decision of not having tests. The alternative to this is manually testing that every page in the website loads. – Cristian Lupascu Mar 27 '12 at 19:46
  • It's not a decision, I want to know if there's another consistent and reliable way to achieve this other than unit tests, which is, as of now, the only way I'm aware of. – Matteo Mosca Mar 27 '12 at 19:47
  • Why would you not be able to use a one method unit test? – Chriseyre2000 Mar 27 '12 at 20:34
  • I was talking about IoC and I got told about IoC not being "compile time safe" and "unit tests add more complexity and are harder to mantain". So I thought I was missing something (because I usually use IoC and when things get complex I throw in some tests) and I was asking here if someone with more experience than me could tell me of a better way of doing this, or confirming the fact that IoC is a bad practice because it allows you to compile but fail at runtime. – Matteo Mosca Mar 27 '12 at 20:38

4 Answers4

10

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.
Steven
  • 166,672
  • 24
  • 332
  • 435
  • Your answer is really appreciated, but I think you got wrong what I'm trying to understand. I don't need to check whether my registered services are resolved correctly. What I need to check is that every service that is requested by code has a registration in the configuration. And I want to understand if IoC can be considered a bad or dangerous practice is this thing cannot be done. – Matteo Mosca Mar 27 '12 at 20:34
  • 1
    You shouldn't request your services from your code. Instead, inject all services through constructor injection and resolve only the root objects. This way a complete object graph is constructed in one go, and this way you know that all services are registered correctly when your root objects are resolved correctly. – Steven Mar 27 '12 at 21:34
  • Yeah I meant the root objects by that. – Matteo Mosca Mar 27 '12 at 22:10
  • 1
    @neeohw, there is certainly a lot truth in your comment, which is what I started to realize in recent years as well. The practice you are referring to is called Pure DI (i.e. practicing DI without a container). For smaller applications, I prefer the use of Pure DI. For larger applications, I prefer the features (like Auto-Registration and convention over configuration) that DI Containers provide. But your mileage might vary. But in the loose coupling is the major part. Using a DI Container or not should be an implementation detail. – Steven May 23 '20 at 18:50
4

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.

Community
  • 1
  • 1
Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
  • You're right, I'm not doing Service Locator but DI, as it is more scalable and manteinable. I think Service Locator is really an antipattern. I tend to have singleton container instance with a generic Resolve method, which internally will use my IoC container of choice. I ask it to resolve a T object, and he will instantiate it, resolving its dependencies through DI. My question was all about understanding if the statement "IoC is bad because your code compiles but could be broken" holds any water and if there was an alternative to Unit Test it (because tests are considered complexity). – Matteo Mosca Mar 27 '12 at 22:16
  • @MatteoMosca: didn't I answer that question here? I've demonstrated that you can have IoC and compile time safety, without unit tests. – Wim Coenen Mar 28 '12 at 08:20
  • Yes and no. I'm not willing to give up a container or the IoC framework of choice in favor of this. I wanted to know if my "need" could be satisfied at the specified conditions, and after all the answers and comments it's pretty clear that the answer is no, which is what I thought from the beginning. Thanks for the help. – Matteo Mosca Mar 29 '12 at 07:42
2

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.

Dmitriy Startsev
  • 1,442
  • 10
  • 19
  • I wholeheartedly agree with you. That's what I usually do anyway, I just wanted to know if there was a feasible alternative. – Matteo Mosca Mar 27 '12 at 22:12
  • "You can't test all of your code with a compiler at build time. It sounds absurd. " Why? A compiler is a program that responds to instructions. There's no inherent reason that a language couldn't provide couldn't support a compile meta-program for testing. – Ritch Melton Mar 27 '12 at 22:53
  • 1
    The compiler holds only static code analysis. But does not run it. Registration and resolving of components occurs at run time. – Dmitriy Startsev Mar 28 '12 at 06:06
1

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

Yair Halberstadt
  • 5,733
  • 28
  • 60