皮下注射C++依赖性注射:"resolve"超类型的对象
C++ dependency injection with hypodermic: "resolve" Objects of a super-type
给出如下类层次结构:
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
和一个AbstractPanel
, Hypodermic是不知道的,也就是说,你必须告诉它自己。
ContainerBuilder builder;
builder.registerType< Component >(CREATE(new Component()))
->named< AbstractComponent >("bkgrd_param_component")
->named< AbstractPanel >("bkgrd_param_component");
这样,Component
被称为AbstractComponent
和AbstractPanel
命名为"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
相关文章:
- 给定一个指向对象的超类指针,如何获取对象的大小?
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 确保指向超类的指针指向c++中某个子类的对象
- 按值将对象传递给 SubClass 构造函数,导致超类的构造函数不调用
- 如何在接口类中创建一个超类对象
- cpp 从需要超类对象的函数访问子类对象方法
- 制作可以存储子类对象的超类类型的向量
- C++检查对象是否是给定超类的后代
- C++编译器如何知道具有超类的对象的大小
- 将子类对象传递给采用超类对象的函数
- 创建子类对象时, 是为超类创建的第二个对象
- 如何检索添加到由其超类对象组成的集合中的派生对象
- 访问超类类型成员对象的受保护成员 - 一个优雅的解决方案
- 当对象不是动态分配的(不是指针)时,是否可以从超类对象转换到子类
- 如何将对象'cast'为其超类继承的类?
- c++继承.对象调用超类方法而不是自己的方法
- 如何调用一个方法,该方法需要一个子类对象,该子类对象由指向其超类的指针引用
- 为什么我们需要一个超类的指针指向子类的对象?
- 在超类需要参数的地方构造不带参数的对象
- 通过值将子类对象传递给接受超类对象的函数是定义良好的行为吗