You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Boost::ex.DI注入带特定参数值的接口实例?

使用Boost.DI注入带特定构造参数的接口实例

要实现给User和Square类分别注入带对应类名字符串的InterfaceImplementation实例,可以利用Boost.DI的条件绑定和构造参数指定功能,具体实现如下:

1. 基础类定义

首先完善接口和实现类的定义(添加虚析构确保多态安全):

#include <boost/di.hpp>
#include <string>
#include <memory>
#include <type_traits>

namespace di = boost::di;

class Interface {
public:
    virtual ~Interface() = default;
};

class InterfaceImplementation : public Interface {
public:
    explicit InterfaceImplementation(std::string s) : instance_name(std::move(s)) {}
private:
    std::string instance_name;
};

2. 依赖类定义

让User和Square的构造函数直接依赖Interface智能指针:

class User {
public:
    explicit User(std::unique_ptr<Interface> iface) : interface(std::move(iface)) {}
private:
    std::unique_ptr<Interface> interface;
};

class Square {
public:
    explicit Square(std::unique_ptr<Interface> iface) : interface(std::move(iface)) {}
private:
    std::unique_ptr<Interface> interface;
};

3. 配置Boost.DI注入器

通过di::when(di::is<T>())限定绑定的适用场景,结合di::with(di::args(...))传递构造参数:

int main() {
    auto injector = di::make_injector(
        // 当User依赖Interface时,注入带"User"参数的实例
        di::bind<Interface>()
            .to<InterfaceImplementation>()
            .in(di::unique) // 每个User获得独立实例,需单例可改为di::singleton
            .when(di::is<User>())
            .with(di::args(std::string{"User"})),

        // 当Square依赖Interface时,注入带"Square"参数的实例
        di::bind<Interface>()
            .to<InterfaceImplementation>()
            .in(di::unique)
            .when(di::is<Square>())
            .with(di::args(std::string{"Square"}))
    );

    // 创建实例,框架自动注入对应参数的Interface实现
    auto user = injector.create<std::unique_ptr<User>>();
    auto square = injector.create<std::unique_ptr<Square>>();

    return 0;
}

关键说明

  • di::when(di::is<T>()):该绑定规则仅在Interface被类型T依赖时生效,避免同接口多绑定的冲突。
  • di::with(di::args(...)):显式指定InterfaceImplementation构造函数的参数值。
  • in(di::unique):控制实例生命周期,di::unique表示每次注入创建新实例,di::singleton则复用同一实例。

内容的提问来源于stack exchange,提问作者Moravas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:30:48