7bitcoder / 7bitDI

Simple C++17 dependency injection library

Home Page:https://7bitdi.readthedocs.io/en/latest/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

DevCI MainCI

logo

C++17 simple dependency injection library!

7bitDI is a simple C++ dependency injection library, designed to be as easy to use as possible, the main inspiration was the asp net core dependency injection system.

Documentation & Examples


Built With

Sample Usage

#include <SevenBit/DI.hpp>
#include <iostream>

using namespace sb::di;

struct IServiceA
{
    virtual std::string actionA() = 0;

    virtual ~IServiceA() = default;
};

struct IServiceB
{
    virtual std::string actionB() = 0;

    virtual ~IServiceB() = default;
};

struct ServiceA final : public IServiceA
{
    std::string actionA() { return "actionA"; }
};

struct ServiceB final : public IServiceB
{
    std::string actionB() { return "actionB"; }
};

class ServiceExecutor
{
    IServiceA *_serviceA;
    std::unique_ptr<IServiceB> _serviceB;

  public:
    ServiceExecutor(IServiceA *serviceA, std::unique_ptr<IServiceB> serviceB)
    {
        _serviceA = serviceA;
        _serviceB = std::move(serviceB);
    }

    std::string execute() { return _serviceA->actionA() + ", " + _serviceB->actionB() + " executed."; }
};
int main()
{
    IServiceProvider::Ptr provider = ServiceCollection{}
                                         .addSingleton<IServiceA, ServiceA>()
                                         .addTransient<IServiceB, ServiceB>()
                                         .addScoped<ServiceExecutor>()
                                         .buildServiceProvider();

    ServiceExecutor &executor = provider->getService<ServiceExecutor>();

    std::cout << executor.execute();
    return 0;
}

Output

actionA, actionB executed.

More examples and tutorials are available on the Documentation & Examples page

@7bitcoder Sylwester Dawida 2023

About

Simple C++17 dependency injection library

https://7bitdi.readthedocs.io/en/latest/

License:MIT License


Languages

Language:C++ 95.6%Language:CMake 4.3%Language:Python 0.2%