Skip to content

Multiple bindings should allow duplicates and merge the bindings #340

Open
@azureblaze

Description

@azureblaze

Similar to dagger multiple binding
https://google.github.io/dagger/multibindings.html

auto base = [] {
  di::makeInjector(
    di::bind(int []).to({1})
  );
};

auto injector = di::make_injector(
  base(),
  di::bind(int []).to({2});
);
auto s = injector.create<std::set<int>>();
assert(s.size() == 2);
assert(s.count(1) == 1);
assert(s.count(2) == 1);

This allows a client to inject event listeners into a library.
for example,

class Interface{};
using Factory = function<unique_ptr<Interface>()>;
struct FactoryEntry{
  stirng key;
  Factory factory;
};
struct CreateWithStringFactory{
  map<string,  Factory> factories;
  CreateWithStringFactory(set<FactoryEntry> entries) {
    for(auto entry : entries){
      map[entry.name] = entry.factory
    }
  }
  
  unique_ptr<Interface> create(const string name&) {
    return map[name]();
  }
};

auto libraryModule = []() { 
  return di::make_injector(
      di::bind<Factory []>.to(FactoryEntry{"foo", di::extension::assisted_injection<Foo>()})
  );
};

...

auto injector = di::make_injector(
  libraryModule (),
  di::bind<Factory []>.to(FactoryEntry{"bar", di::extension::assisted_injection<Bar>()})
);

auto createWithStringFactory = di.create<CreateWithStringFactory>();

assert(dynamic_cast<Bar>(createWithStringFactory.create("bar")) != nullptr);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions