Has anyone started a project to do IOC at compile time (possibly using Roslyn or Linq MethodInfo emit)?
My experience with IOC containers has thus far been great, baring a few small issues
- Many IOC containers are slow to start up, as much of the resolution logic occurs here
- It is often hard to ensure that resolution is possible, as compilation no longer ensures that the constructor can be called
- Often IOC containers add a small overhead to the runtime (some aren’t even small, often the ones that start up quickly run slowly)
It seems to me that the ideal solution would be to add a compile step to the build chain that adds a Factory class instead of IOC.
Has anyone done this before? If not, why not?
Doing this should not be such a problem. Just run same IoC logic and instead of instantiating the classes, you emit code that does the instantiating.
But by doing this, you are removing one huge advantage of IoC : Ability to change how the coponents are composed without having to recompile the whole application. Just by replacing the config, you can have application use different services or data sources. And while I have yet to see application that would make full use of this capability, it is still major part of IoC’s success.
4
Dagger for Java/Android does that. It sacrifices some runtime magic (like Guice’s) to offer an almost completely compile-time codegen experience, including converting most runtime errors to compilation errors.
Would be cool in .NET too.
I’m working on a project to do exactly this, using Roslyn’s preview SourceGenerators. It does all the wiring up at compile time, and gives you compiler errors/warnings if you make a mistake.
Try it out at https://github.com/YairHalberstadt/stronginject