皮下注射C++依赖性注射:"resolve"超类型的对象

C++ dependency injection with hypodermic: "resolve" Objects of a super-type

本文关键字:对象 超类 类型 resolve C++ 依赖性      更新时间:2023-10-16

给出如下类层次结构:

class AbstractPanel
{ }
class AbstractComponent : public AbstractPanel
{ }
class Component : public AbstractComponent
{ }

及以下注射用DI容器:

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

根据上下文的不同,resolve()调用看起来像这样:

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

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

两个调用都返回一个nullptr,尽管我注册的对象类型都是"AbstractPanel"answers"AbstractComponent"。

我该如何设计这个?我不能改变类的层次结构,但是我想根据对象的名字来解析它。

有谁有主意吗?

问候,Vandahlen

虽然你的Component是一个AbstractComponent和一个AbstractPanelHypodermic是不知道的,也就是说,你必须告诉它自己。

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

这样,Component被称为AbstractComponentAbstractPanel 命名为"bkgrd_param_component"和您给出的分辨率:

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

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

将为提供Component类型的两个不同的实例。

有一个新的非侵入性版本皮下你可以使用。Dsl更优雅一点:

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

查看它的wiki