Using Factories¶
Factory functor can be provided to manually create a service. Functor should return unique_ptr or raw object if the type 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 an object is movable or copyable), unique pointers, references, vectors with pointers or unique pointers
Examples/Guides/FactoryFunctions¶
#include <SevenBit/DI.hpp>
#include <iostream>
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.