用水果注入C++依赖

C++ dependency injection with fruit

本文关键字:C++ 依赖 注入      更新时间:2023-10-16

我有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>>();
}