0

given the following class hierarchy:

class AbstractPanel
{ }

class AbstractComponent : public AbstractPanel
{ }

class Component : public AbstractComponent
{ }

and the following Hypodermic DI Container:

Hypodermic::ContainerBuilder builder;
builder.registerType<Component>( CREATE(new Component()) )->as<Component>()->named<Component>("bkgrd_param_component");
(... and adding it to "di_container")

Depending on the Context, a resolve()-Call looks like this:

di_container->resolveNamed<AbstractComponent>("bkgrd_param_component")

or

di_container->resolveNamed<AbstractPanel>("bkgrd_param_component")

Both calls return a nullptr, although my registered Object is both of type "AbstractPanel" and "AbstractComponent".

How do I have to design this? I can't change the class-hierarchy but want to resolve the Object, depending on its name.

Does anybody have an idea?

Regards, Vandahlen

VanDahlen
  • 93
  • 6

1 Answers1

0

Although your Component is an AbstractComponent and an AbstractPanel, Hypodermic isn't aware of that, that is, you have to tell it yourself.

ContainerBuilder builder;

builder.registerType< Component >(CREATE(new Component()))
       ->named< AbstractComponent >("bkgrd_param_component")
       ->named< AbstractPanel >("bkgrd_param_component");

That way, Component is known as both AbstractComponent and AbstractPanel named "bkgrd_param_component" and the resolutions you gave:

container->resolveNamed< AbstractComponent >("bkgrd_param_component")

and

container->resolveNamed< AbstractPanel >("bkgrd_param_component")

will provide two different instances of the type Component.

There is a new non-intrusive version of Hypodermic you could use. The Dsl is a bit more elegant:

ContainerBuilder builder;

builder.registerType< Component >()
       .named< AbstractComponent >("bkgrd_param_component")
       .named< AbstractPanel >("bkgrd_param_component");

Have a look at its wiki.

mister why
  • 1,967
  • 11
  • 33