IoC container, check for errors at compile time

2019-01-11 11:15发布

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"?

3条回答
闹够了就滚
2楼-- · 2019-01-11 11:43

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.

查看更多
Ridiculous、
3楼-- · 2019-01-11 11:56

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.

查看更多
乱世女痞
4楼-- · 2019-01-11 12: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.
查看更多
登录 后发表回答