Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IoC container, check for errors at compile time

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

like image 740
Matteo Mosca Avatar asked Mar 27 '12 19:03

Matteo Mosca


1 Answers

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

like image 62
Yair Halberstadt Avatar answered Oct 20 '22 00:10

Yair Halberstadt