简体   繁体   中英

DI Boost C++14 and dynamic containers

First of all the Boost.DI looks like very useful tool to create code based on dependency injection in C++14. It's very good documented and I created basic application using the Boost.DI quite fast, but what I still can figure out is how to deal with dynamically initialized containers of objects with some injected dependencies. Boost.DI will initialize whole application class tree in main on application start via injector object, but what if I have for example some class "Foo" with load method which takes xml resource and wants to create bunch of objects "Bar" (with some dependencies on already created modules) based on that resource. Should I pass injector object into the Foo, or inject some factory into the Foo and create Bars in that factory? Injecting the injector seems really weird and make injector global leads to dangerous situation where anybody can create anything. Injecting the factory only moves same problem somewhere else, how factory can create Bars without the injector object?

In your scenario it sounds like you can take from the Foo class all the logic that knows how to load the XML and create a Bar , and have this logic called from a factory lambda that you would bind to Bar when you create the injector.

If the logic that loads the XML and creates the Bar depends on other classes that need to be created by an injector, then this injector will be the parameter that your factory lambda receives. It doesn't have to be a global injector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM