Using Factories#

Factory functor can be provided to manually create a service. Functor should return unique_ptr or T if object is movable/copyable and should optionally take other services as arguments. Functor scheme (Services…) -> std::unique_ptr< T> | T Where Services are pointers, in place objects (if object is movable or copyable), unique pointers, references, vectors with pointers or unique pointers

Examples/Guides/FactoryFunctions#
#include <SevenBit/DI.hpp>
#include <iostream>
#include <memory>
#include <utility>

using namespace sb::di;

class ServiceA
{
    std::string _message;

  public:
    explicit ServiceA(std::string message) { _message = std::move(message); }

    std::string message() { return _message; }
};

class ServiceB
{
    ServiceA &_serviceA;

  public:
    explicit ServiceB(ServiceA &serviceA) : _serviceA(serviceA) {}
    ServiceB(ServiceB &&) = default;

    [[nodiscard]] std::string message() const { return _serviceA.message(); }
};

int main()
{
    ServiceProvider provider =
        ServiceCollection{}
            .addSingleton<ServiceA>([] { return std::make_unique<ServiceA>("Hello from service!"); })
            .addSingleton<ServiceB>([](ServiceA &serviceA) { return ServiceB(serviceA); })
            .buildServiceProvider();

    auto &serviceA = provider.getService<ServiceA>();
    const auto &serviceB = provider.getService<ServiceB>();

    std::cout << serviceB.message();

    return 0;
}
Output#
Hello from service.