06 Oct 2012
An open-source, header-only C++ dependency injection library.
Inject is intended to be a C++ dependency injection library which:
- is header-only - library does not require anything but including its header files
- is non-intrusive -any class can be a component. No need to inherit library interfaces, declare mandatory members or include a macro in the class declaration. For a class to be a component all it needs is to have its default-constructor public and functioning
- is macro-less -the library does not rely on pre-processing magic for code-generation. Noneed to declare constructors in a special way or include black-magic macros in your class' body
- is declarative - this is similar to the non-intrusive bullet. Using a class as a component is a matter of declaration, which is done separately from the class' declaration
- doesn't require code-generation - the library relies only on the standard code generation facilities offeredby C++98 through the template mechanism. No additional scripts/executables need to be run to get injections functionality to the application
- is very simple to use
- fully supports allocation and instantiation through std::allocator
- supports up to 10 constructor arguments
- can inject to setter methods
- does not use RTTI
- is fully C++98 complaint
The full projects is available on the priejct's GitHub page.
Here is a quick example: (full example)
#include <string> #include <iostream> // our header #include <inject/inject.h> // interface to inject service to class service { public: virtual const std::string name() const = 0; }; // declare 'service' as an injection component in the default injection context context<>::component<service> service_decl; // service implementation class impl : public service { public: virtual const std::string name() const { return "impl"; } }; // declare 'impl' component and declare it as a provider of the 'service' service component context<>::component<impl> impl_decl; context<>::component<impl>::provides<service> impl_provides_decl; // declare 'impl' as the default implementation of 'service' context<>::component<service>::implemented_by<impl> service_impl_decl; int main() { // request a pointer to the component that provides 'service' context<>::injected<service> serv_inst; // prints 'impl' std::cout << serv_inst->name() << std::endl; return 0; }