Boost.DI: dependency injection in C ++
- Transfer
- Tutorial
“Do not call us. We will call you ourselves. ” - Hollywood principle
Dependency Injection (DI) means transferring (introducing) one or more dependencies to any object (client, component) in such a way that after implementation this dependence becomes part of the state of the object. This is a bit like the design pattern Strategy, with the only difference being that the strategy is set only once - in the constructor. DI allows you to create a more loosely coupled application architecture that lends itself better to support and testing.
So, pluses again:
Boost.DI is a library for implementing dependency injection in C ++. To use it, you just need to include one header file in your code. The purpose of the library is to simplify the creation of objects using automatic dependency injection:

In general, everything you need to work with the library, this di.hpp file
Let's assume that all the examples below include boost / di.hpp and define the di namespace as alias boost :: di.
Examples
More examples
Examples
More examples
Examples
Примеры
Ещё примеры

Примеры
Примеры
Примеры
Ещё примеры
Окружение
Пример
Окружение
Легенда



License: Boost Software License, Version 1.0
Nuance: the library is not yet included in Boost, but is only located in the " incubator ".
Dependency Injection (DI) means transferring (introducing) one or more dependencies to any object (client, component) in such a way that after implementation this dependence becomes part of the state of the object. This is a bit like the design pattern Strategy, with the only difference being that the strategy is set only once - in the constructor. DI allows you to create a more loosely coupled application architecture that lends itself better to support and testing.
So, pluses again:
- Decreases component connectivity (separates business logic from object creation)
- Allows you to write more supported code (we can easily implement different dependencies in the same objects)
- Allows you to write more testable code (we can use stubs and moki more easily)
No dependency injection | With dependency injection |
---|---|
|
|
Boost.DI is a library for implementing dependency injection in C ++. To use it, you just need to include one header file in your code. The purpose of the library is to simplify the creation of objects using automatic dependency injection:
- Reducing the number of bottlenecks in the code - no extra factories, no creation of objects in only a certain order
- Simplified code support - changing the designer signature will not affect DI configuration
- Simplified Testing - Automatic Mock Injection
- Better control over what and when to create
- Better understanding of the code in terms of the hierarchy of objects
Manual Dependency Injection | Boost.DI |
---|---|
|
|
Once again - why use dependency injection

Where to begin?
- Take a compiler with C ++ 14 support (Clang-3.4 +, GCC-5.0 +). Boost library not required
- Read this document
- Read the tutorial
- Read the documentation
In general, everything you need to work with the library, this di.hpp file
// main.cpp
#include "di.hpp"
int main() { }
$CXX -std=c++1y -I. main.cpp
Let's assume that all the examples below include boost / di.hpp and define the di namespace as alias boost :: di.
#include
namespace di = boost::di;
//
struct i1 { virtual ~i1() = default; virtual void dummy1() = 0; };
struct i2 { virtual ~i2() = default; virtual void dummy2() = 0; };
struct impl1 : i1 { void dummy1() override { } };
struct impl2 : i2 { void dummy2() override { } };
struct impl : i1, i2 { void dummy1() override { } void dummy2() override { } };
Injector
Create an empty injector | Test |
---|---|
|
|
Bindings
Examples
More examples
Binding an interface to an implementation | Test |
---|---|
|
|
Binding multiple interfaces to one implementation | Test |
---|---|
|
|
Binding a type to a value computed at compile time | Test |
---|---|
|
|
Binding a Type to a Value | Test |
---|---|
|
|
Implementation
Examples
More examples
Deploy through a regular constructor | Test |
---|---|
|
|
Implementation through Aggregation | Test |
---|---|
|
|
Implementation through the constructor if there are several constructors (the one with the largest number of parameters will be selected ) | Test |
---|---|
|
|
Deployment through the constructor when there are choices (using BOOST_DI_INJECT) | Test |
---|---|
|
|
Deployment through the constructor when there are choices (using BOOST_DI_INJECT_TRAITS) | Test |
---|---|
|
|
Deployment through the constructor when there are choices (using di :: ctor_traits) | Test |
---|---|
|
|
Annotations
Examples
Deploy through annotated constructors | Test |
---|---|
|
|
Deploy through annotated constructors using named parameters | Test |
---|---|
|
|
Implementation through annotated constructors with the implementation of the constructor implementation | Test |
---|---|
|
|
Внедрение через аннотированные конструкторы с использованием di::ctor_traits | Тест |
---|---|
|
|
Области видимости
Примеры
Ещё примеры
Вывод области видимости (по-умолчанию) | Тест |
---|---|
|
|
Тип | Выведенная область видимости |
---|---|
T | unique |
T& | ошибка — должен быть связан как external |
const T& | unique (временный) |
T* | unique (передача владения) |
const T* | unique (передача владения) |
T&& | unique |
unique_ptr | unique |
shared_ptr | singleton |
weak_ptr | singleton |
Уникальная область видимости | Тест |
---|---|
|
|
Разделяемая область видимости (в пределах потока) | Тест |
---|---|
|
|
Синглтон (разделяем между потоками) | Тест |
---|---|
|
|
Область видимости сессии | Тест |
---|---|
|
|
Внешняя область видимости | Тест |
---|---|
|
|
Специальная область видимости | Тест |
---|---|
|
|

Модули
Примеры
Модуль | Тест |
---|---|
|
|
Модуль, открывающий тип | Тест |
---|---|
|
|
Модуль, открывающий несколько типов | Тест |
---|---|
|
|
Модуль открытого типа с аннотацией | Тест |
---|---|
|
|
Провайдеры
Примеры
«no throw»-провайдер | Тест |
---|---|
|
|
Политики
Примеры
Ещё примеры
Определение политик конфигурации (дамп типов) | Тест |
---|---|
|
|
Определение политик конфигурации (развёрнутый дамп типов) | Тест |
---|---|
|
|
Политика «может быть сконструирован» | Тест |
---|---|
|
|
Производительность на рантайме
Окружение
- x86_64 Intel® Core(TM) i7-4770 CPU @ 3.40GHz GenuineIntel GNU/Linux
- clang++3.4 -O2 / gdb -batch -ex 'file ./a.out' -ex 'disassemble main'
Создание типа без привязок | Asm x86-64 (то же, что «return 0») |
---|---|
|
|
Создание типа с привязкой объекта | Asm x86-64 (то же, что «return 42») |
---|---|
|
|
Создание именованного типа | Asm x86-64 (то же, что «return 42») |
---|---|
|
|
Создание привязки интерфейса к реализации | Asm x86-64 (то же, что «make_unique») |
---|---|
|
|
Создание привязки интерфейса через модуль | Asm x86-64 (то же, что «make_unique») |
---|---|
|
|
Создание привязки интерфейса через открытый модуль | Asm x86-64 цена = вызов виртуального метода |
---|---|
|
|
Производительность на этапе компиляции
Пример
Окружение
- x86_64 Intel® Core(TM) i7-4770 CPU @ 3.40GHz GenuineIntel GNU/Linux
- clang++3.4 -O2
Заголовочный файл Boost.DI | Время [сек] |
---|---|
| 0.165 |
Легенда
- ctor = «голый» конструктор: c(int i, double d);
- inject = внедрение в конструктор: BOOST_DI_INJECT(c, int i, double d);
- all = все типы в модуле доступны: auto configure();
- exposed = один тип в модуле доступен: di::injector
configure();

- 4248897537 объектов создано
- 132 разных типа
- 10 модулей

- 1862039751439806464 объекта создано
- 200 разных типов
- 10 модулей

- 5874638529236910091 объект создан
- 310 разных типов
- 100 разных интерфейсов
- 10 модулей
Диагностические сообщения
Создание интерфейса без привязки к реализации | Сообщение об ошибке |
---|---|
|
|
Неоднозначность привязки | Сообщение об ошибке |
---|---|
|
|
Создание объекта без привязок при политике, требующей их | Сообщение об ошибке |
---|---|
|
|
Неверный синтаксис аннотаций (NAMED вместо named) | Сообщение об ошибке |
---|---|
|
|
Конфигурация
Макрос | Описание |
---|---|
|
|
Похожие библиотеки
License: Boost Software License, Version 1.0
Nuance: the library is not yet included in Boost, but is only located in the " incubator ".