Skip to content

Fallback registrations

Andreone edited this page May 11, 2017 · 3 revisions

You should keep in mind that Hypodermic will resolve a type by using its last registration.

ContainerBuilder builder;

builder.registerType< MessageDispatcher >().as< IMessageDispatcher >();
builder.registerType< NoopMessageDispatcher >().as< IMessageDispatcher >();

auto container = builder.build();

// This will return an instance of NoopMessageDispatcher... d'uh
auto dispatcher = container->resolve< IMessageDispatcher >();

As your application grows in size and complexity, some modules will register themselves in the container and might provide some default implementations. To be free from knowing in which order the modules should be registered, default/fallback registrations can be tagged via useIfNone.

ContainerBuilder builder;

builder.registerType< MessageDispatcher >()
       .as< IMessageDispatcher >();

builder.registerType< NoopMessageDispatcher >()
       .as< IMessageDispatcher >()
       .useIfNone();

auto container = builder.build();

// This will return an instance of MessageDispatcher
auto dispatcher = container->resolve< IMessageDispatcher >();
Clone this wiki locally