项目作者: GracjanP

项目描述 :
Dependency injection library for C++
高级语言: C++
项目地址: git://github.com/GracjanP/cppdi.git
创建时间: 2018-08-18T23:50:21Z
项目社区:https://github.com/GracjanP/cppdi

开源协议:MIT License

下载


cppdi

cppdi is a header-only c++17 library that brings dependency injection to C++. It’s heavily inspired by DI provided by ASP.NET.

Installation

Simply drop the header file in your project or add the include directory to your include paths.

Usage

Here’s a simple example of using the dependency injection container.

  1. #include <iostream>
  2. #include "Container.hpp"
  3. class IGreeter
  4. {
  5. public:
  6. virtual void Greet() = 0;
  7. }
  8. class HelloWorldGreeter : public IGreeter
  9. {
  10. public:
  11. void Greet() override
  12. {
  13. std::cout << "Hello, world!\n";
  14. }
  15. }
  16. int main()
  17. {
  18. cppdi::Container container;
  19. container.AddSingleton<IGreeter, HelloWorldGreeter>();
  20. auto greeter = container.GetRequiredService<IGreeter>();
  21. greeter->Greet();
  22. return 0;
  23. }

This outputs Hello, world!

Non-parameterless constructors

If your class doesn’t have a parameterless constructor (which is usually the case) you’ll have to create a template specialization for your types in cppdi namespace. An example specialization will look like this:

  1. namespace cppdi
  2. {
  3. template <>
  4. std::shared_ptr<ISerializer> CreateInstance<ISerializer, JsonSerializer>(const Container &container)
  5. {
  6. auto configuration = container.GetRequiredService<IConfiguration>();
  7. auto instance = std::make_shared<JsonSerializer>(configuration); // Let's assume that JsonSerializer takes a shared_ptr<IConfiguration> as a parameter
  8. return instance;
  9. }
  10. }

There are more ways you can register implementations of interfaces and they are documented in the Container.hpp file.