[英]C++ dependency injection with fruit
我有A類和接口IInterface。 我需要向A中注入2個成員IInterface。
所以:
class A {
IInterface* i1;
IInterface* i2;
};
我可以使用水果DI框架將2個成員(i1和i2)注入A嗎?
我是水果作者(感謝艾倫(Alan)指出我這個話題!)。 注入該類的最簡單方法是構造函數注入。 假設兩個接口相同(如您的示例中所示),並且您想要2個不同的實例,則可以使用帶注釋的注入,如下所示:
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>();
}
帶注釋的注入是Fruit 2.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>>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.