How to inject a value known only at runtime using boost-di?

Viewed 201

I am learning to use boost::di and I fail to understand how one is expected to create multiple instances of the same type using different runtime parameters.

From what I understand, The documentation mostly focuses on creating a single object with the same parameters. I would like to create multiple objects using parameters that are known at runtime.

For example, I have the following type:

struct Device
{
    int slot_; 
    Device(int slot) : slot_(slot) {}
};

The slot variable is determined only at runtime via user input.

Ideally, I would like to be able to do something like this:

auto device1 = injector.create<std::shared_ptr<Device>>(123); // slot = 123
auto device2 = injector.create<std::shared_ptr<Device>>(321); // slot = 321

Based on the documentation, This is what I managed so far:

auto injector = di::make_injector(
        di::bind<Device>.to(
            [&](const auto& injector)
            {
                // this assumes slot is a captured by the lambda
                return std::make_shared<Device>(slot);
            })
    );

int slot = 123; // captured by lambda
auto device1 = injector.create<std::shared_ptr<Device>>();
slot = 321; // captured by lambda
auto device2 = injector.create<std::shared_ptr<Device>>();

I would like to avoid capturing the slot variable by the lambda. My real use case involves many runtime parameters for each type.

  • Is there a more elegant way to pass the runtime parameters to the injector at runtime?
  • What is the generic way to pass runtime parameters to constructors with boost::di?
0 Answers
Related