使用依赖注入注入参数

Injecting parameters with 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>();
}

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

error C2672: 'boost::ext::di::v1_2_0::core::injector<TConfig,boost::ext::di::v1_2_0::core::poolboost::ext::di::v1_2_0::aux::type_list<>,boost::ext::di::v1_2_0::core::dependency<TScope,TExpected,T,TName,TPriority,TCtor>,boost::ext::di::v1_2_0::core::dependency<TScope,IB,B,TName,TPriority,TCtor>,boost::ext::di::v1_2_0::core::dependency<TScope,IC,C,TName,TPriority,TCtor>>::create': no matching overloaded function found with [ TConfig=boost::ext::di::v1_2_0::config, TScope=boost::ext::di::v1_2_0::scopes::deduce, TExpected=IA, T=A, TName=boost::ext::di::v1_2_0::no_name, TPriority=void, TCtor=boost::ext::di::v1_2_0::core::none ]

error C2770: invalid explicit template argument(s) for 'T boost::ext::di::v1_2_0::core::injector<TConfig,boost::ext::di::v1_2_0::core::poolboost::ext::di::v1_2_0::aux::type_list<>,boost::ext::di::v1_2_0::core::dependency<TScope,TExpected,T,TName,TPriority,TCtor>,boost::ext::di::v1_2_0::core::dependency<TScope,IB,B,TName,TPriority,TCtor>,boost::ext::di::v1_2_0::core::dependency<TScope,IC,C,TName,TPriority,TCtor>>::create(void) const' with [ TConfig=boost::ext::di::v1_2_0::config, TScope=boost::ext::di::v1_2_0::scopes::deduce, TExpected=IA, T=A, TName=boost::ext::di::v1_2_0::no_name, TPriority=void, TCtor=boost::ext::di::v1_2_0::core::none ]

note: see declaration of 'boost::ext::di::v1_2_0::core::injector<TConfig,boost::ext::di::v1_2_0::core::poolboost::ext::di::v1_2_0::aux::type_list<>,boost::ext::di::v1_2_0::core::dependency<TScope,TExpected,T,TName,TPriority,TCtor>,boost::ext::di::v1_2_0::core::dependency<TScope,IB,B,TName,TPriority,TCtor>,boost::ext::di::v1_2_0::core::dependency<TScope,IC,C,TName,TPriority,TCtor>>::create' with [ TConfig=boost::ext::di::v1_2_0::config, TScope=boost::ext::di::v1_2_0::scopes::deduce, TExpected=IA, T=A, TName=boost::ext::di::v1_2_0::no_name, TPriority=void, TCtor=boost::ext::di::v1_2_0::core::none ]

知道我做错了什么吗?

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

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

Demo