使用依赖注入注入参数

时间:2021-05-21 12:30:12

标签: c++ boost dependency-injection

我正在尝试在我的项目中设置依赖项注入 (https://boost-ext.github.io/di/) 并收到以下编译错误错误“找不到匹配的重载函数”和“无效的显式模板参数”。

我的测试设置如下

#include "di.hpp"
namespace di = boost::di;

class IA{
public:
    virtual void doSomething() = 0;
};

class IB{
public:
    virtual void doSomething() = 0;
};

class IC{
public:
    virtual void doSomething() = 0;
};

class A : public IA {
public:
    void doSomething() override {
    }
};

class B : public IB {
public:
    void doSomething() override {

    }
};

class C : public IC{
    std::shared_ptr<A> a_;
    std::shared_ptr<B> b_;
public:
    C(std::shared_ptr<A> a, std::shared_ptr<B> b) : a_(a), b_(b){}
    void doSomething() override {
    }
};

int main(int argc, char *argv[]) {

    const auto injector = di::make_injector(
            di::bind<IA>.to<A>(),
            di::bind<IB>.to<B>(),
            di::bind<IC>.to<C>()
    );
    auto test = injector.create<IC>();
}

以下是我的编译错误的详细信息:

<块引用>

错误 C2672:'boost::ext::di::v1_2_0::core::injector,boost::ext::di::v1_2_0::core::dependency,boost::ext::di::v1_2_0 ::core::dependency,boost::ext::di::v1_2_0::core::dependency> ::create': 找不到匹配的重载函数 和 [ TConfig=boost::ext::di::v1_2_0::config, TScope=boost::ext::di::v1_2_0::scopes::deduce, T预期=IA, T=A, TName=boost::ext::di::v1_2_0::no_name, TPriority=void, TCtor=boost::ext::di::v1_2_0::core::none ]

<块引用>

错误 C2770:'T boost::ext::di::v1_2_0::core::injector,boost::ext::di::v1_2_0::core::dependency,boost ::ext::di::v1_2_0::core::dependency,boost::ext::di::v1_2_0::core::dependency>::create(void) const' 和 [ TConfig=boost::ext::di::v1_2_0::config, TScope=boost::ext::di::v1_2_0::scopes::deduce, T预期=IA, T=A, TName=boost::ext::di::v1_2_0::no_name, TPriority=void, TCtor=boost::ext::di::v1_2_0::core::none ]

<块引用>

注意:参见 'boost::ext::di::v1_2_0::core::injector,boost::ext::di::v1_2_0::core::dependency,boost::ext::di: :v1_2_0::core::dependency,boost::ext::di::v1_2_0::core::dependency>::创建' 和 [ TConfig=boost::ext::di::v1_2_0::config, TScope=boost::ext::di::v1_2_0::scopes::deduce, T预期=IA, T=A, TName=boost::ext::di::v1_2_0::no_name, TPriority=void, TCtor=boost::ext::di::v1_2_0::core::none ]

知道我做错了什么吗?

1 个答案:

答案 0 :(得分:2)

你调用错了,应该类似于:

auto test = injector.create<std::unique_ptr<IC>>();

Demo