Hypodermic is an IoC container for C++. It provides dependency injection to your existing design.
Hypodermic is mostly inspired from the famous .NET Autofac http://code.google.com/p/autofac/. A thousand thanks to its creators.
Components are registered in a ContainerBuilder
.
ContainerBuilder builder;
Considering these classes:
You can invoke ContainerBuilder::registerType()
with a type as a template parameter.
builder.registerType< Driver >();
Further readings: Registering concrete types basics
class Car : public ICar
{
public:
Car(std::shared_ptr< IDriver > driver);
}
Note that Car
is needing to be injected a IDriver
. We need to tell the container that Driver
is actually a IDriver
by setting up this concrete type as an interface:
builder.registerType< Driver >()->as< IDriver >();
Further readings: Registering concrete types as interfaces
Now, we can setup Car
:
builder.registerType< Car >(CREATE(new Car(INJECT(IDriver))))->as< ICar >();
Calling ContainerBuilder::build()
creates a container:
auto container = builder.build();
Now it is time to get our instance:
auto car = container->resolve< ICar >();
That's all folks!