/Hypodermic

Hypodermic is an IoC container for C++. It provides dependency injection to your existing design.

Primary LanguageC++

Hypodermic

Hypodermic is an IoC container for C++. It provides dependency injection to your existing design.

Ackowledgment

Hypodermic is mostly inspired from the famous .NET Autofac http://code.google.com/p/autofac/. A thousand thanks to its creators.

Adding components

Components are registered in a ContainerBuilder.

ContainerBuilder builder;

Registering concrete types

Considering these classes:

Sample class hierarchy

You can invoke ContainerBuilder::registerType() with a type as a template parameter.

builder.registerType< Driver >();

Further readings: Registering concrete types basics

Expressing dependencies

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 >();

Resolving types

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!