用水果注入C++依赖
C++ dependency injection with fruit
我有A类和接口IInterface。我需要在A.中注入2个成员接口
因此:
class A {
IInterface* i1;
IInterface* i2;
};
我可以使用fruit DI框架将2个成员(i1和i2)注入A中吗?
我是Fruit的作者(感谢Alan为我指出这条线索!)。注入该类的最简单方法是构造函数注入。假设这两个接口是相同的(如您的示例中所示),并且您想要两个不同的实例,那么您可以使用带注释的注入,它看起来像:
using namespace fruit;
struct FirstI {};
struct SecondI {};
class A {
IInterface* i1;
IInterface* i2;
public:
INJECT(A(ANNOTATED( FirstI, IInterface*) i1,
ANNOTATED(SecondI, IInterface*) i2))
: i1(i1), i2(i2) {}
};
在get*Component()
函数中,您必须将两者绑定(绑定到同一类型或不同类型,两者完全独立,因为它们有不同的注释):
class FirstIImpl : public IInterface {
....
public:
INJECT(FirstIImpl()) = default;
};
class SecondIImpl : public IInterface {
....
public:
INJECT(SecondIImpl()) = default;
};
Component<A> getAComponent() {
return createComponent()
.bind<fruit::Annotated< FirstI, IInterface>, FirstIImpl>()
.bind<fruit::Annotated<SecondI, IInterface>, SecondIImpl>();
}
注释注入是Fruit2.x中的一个新功能,我还没有时间记录它(抱歉)。希望上面的例子应该是你想要的,如果不让我知道的话。
如果您想将两个接口绑定到同一类型,您还必须对实现类进行注释,以便在注入图中有2个节点(对象),而不是1个。例如:
Component<A> getAComponent() {
return createComponent()
.bind<fruit::Annotated< FirstI, IInterface>,
fruit::Annotated< FirstI, IImpl>>()
.bind<fruit::Annotated<SecondI, IInterface>,
fruit::Annotated<SecondI, IImpl>>();
}
相关文章:
- 如何从C++中的依赖类型中获得它所依赖的类型
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 将依赖名称显式标记为类型名和模板的奇怪之处
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- C++GTKMM gui循环依赖关系
- 通过ccmake在cmake中缓存依赖选项
- 当基类是依赖类型时,这是一个缺陷吗
- 从不同的附加依赖项中识别等同命名的函数
- 如何在 CMake 中对目标依赖项进行分组?
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 为什么构建目录中新构建的共享库与安装目录中的副本具有不同的依赖项集?
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 为什么内存屏障依赖于变量?
- node-gyp 的先有鸡还是先有蛋的问题:指向依赖项中的头文件
- 反转依赖于 end() 的迭代器
- GCC,CMake,预编译标头和维护依赖项
- 使用 'typename' 关键字将非类型视为依赖上下文中的类型
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 为什么依赖模板类型在部分专用化中不可推导?