Skip to content

Registering components

Andreone edited this page May 11, 2017 · 12 revisions

Basic registrations

Register a type

ContainerBuilder builder;

builder.registerType< MessageDispatcher >();

Register an instance

ContainerBuilder builder;

auto configuration = std::make_shared< DispatcherConfiguration >();
builder.registerInstance(configuration);

Register a factory

ContainerBuilder builder;

builder.registerInstanceFactory([](ComponentContext&)
{
    return std::make_shared< ThreadPool >(std::thread::hardware_concurrency());
});

Registrations as abstractions

When registering types, instances, or instance factories, you may want the container to know them by their abstraction(s).

Using As

ContainerBuilder builder;

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

The container will give an instance of MessageDispatcher when it is asked to resolve a IMessageDispatcher.

Note: it will no longer be able to resolve MessageDispatcher when you use as.

Using Named

On an abstraction

ContainerBuilder builder;

builder.registerType< MessageDispatcher >()
       .named< IMessageDispatcher >("LeDispatcher");

auto leDispatcher = container->resolveNamed< IMessageDispatcher >("LeDispatcher");

The container looks up for an implementation of IMessageDispatcher named "LeDispatcher".

Note: it won't be able to resolve IMessageDispatcher if you don't provide the name you gave at the same time.

On the registered type itself

ContainerBuilder builder;

builder.registerType< MessageDispatcher >().named("LeDispatcher");

auto leDispatcher = container->resolveNamed< MessageDispatcher >("LeDispatcher");

Using named without passing a type does two things: letting the container know about the MessageDispatcher implementation named "LeDispatcher" and registering the type as itself. It is basically like calling asSelf.

Using AsSelf

ContainerBuilder builder;

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

This way, you explicitly tell the container that both MessageDispatcher and IMessageDispatcher can be resolvable.

Hooking activation

You can provide a hook when instances are activated by the container. Read the doc here.

Controlling lifetime

You can configure Hypodermic to expand or narrow the lifetime of your registrations. Read this section of the wiki to know how to do it.

Providing fallbacks

Read this section to learn how you can free yourself from registering default components in a particular order.

Clone this wiki locally