r/cpp • u/Acrobatic-Stable2537 n0F4x • Jun 25 '26
C++23 Dependency Injection library with automatic dependency building
I open-sourced my dependency injection library.
Link: https://github.com/n0F4x/redi
This was developed for my game engine.
- feature-rich dependency configuration
- optimized for fast compile time
- helpful error messages when a cyclic dependency is detected
- dependencies are automatically constructed - no need to register them by hand
I am giving this project to the community so that everybody can benefit. This kind of approach is mostly useful when dealing with intricate systems, such as a plugin system. I welcome all kinds of feedback, as this was mostly a learning opportunity for me. If you'd like to use this in your project but don't have access to the required compiler features, let me know, and I'll see if I can reduce the requirements.
View all comments
Show parent comment
1
u/Acrobatic-Stable2537 n0F4x Jun 26 '26
I store a hash for the local dependency types, plus the hash of the current one. This way I can search through the tree when I build all the objects. A downside is that I have to store the names of the objects as well to create a meaningful error message, and it can only detect cycles through registered optional dependencies as opposed to detecting a cycle through all the optional dependencies upon registration.
I used to walk through the tree when you register a type with a pointer to the previous function stack where I store the current type hash. This lets you use the stack as a linked list. At each function call you can iterate through the list and check if you have already visited the current type. The lucky thing is that the compiler only has to generate each function template instantiation once, so you won't run into a recursion that way.