Configuring Service Provider¶
ServiceProviderOptions struct can be used to configure service provider, read comment documentation for details:
Include/SevenBit/DI/ServiceProviderOptions.hpp¶
#pragma once
#include "SevenBit/DI/LibraryConfig.hpp"
namespace sb::di
{
/**
* @brief Options object used to configure service provider
*/
struct ServiceProviderOptions
{
/**
* @brief Set strong service destruction order
* @details If set to true service provider will destruct services in opposite order to construction.
*/
bool strongDestructionOrder = false;
/**
* @brief Set prebuilds singletons
* @details If set to true when service provider is constructed it will also construct all singletons
*/
bool prebuildSingletons = false;
/**
* @brief Set global uniqueness check
* @details If set to true service provider will check if service implementation was already registered and
* throw exception in this case
*/
bool checkServiceGlobalUniqueness = true;
/**
* @brief Set service search strategy
* @details If set to true provider will search for service in singleton container first then in scoped
*/
bool searchInSigletonsFirst = true;
};
} // namespace sb::di
Pass the custom options to the ServiceCollection buildServiceProvider method to change produced service provider behaviour
Examples/Guides/ConfiguredServiceProvider¶
#include <SevenBit/DI.hpp>
#include <cassert>
#include <iostream>
using namespace sb::di;
struct IService
{
virtual std::string action() = 0;
virtual ~IService() = default;
};
struct Service final : IService
{
std::string action() override { return "action"; }
};
class ServiceExecutor
{
IService &_service;
Service &_implService;
public:
explicit ServiceExecutor(IService &service, Service &implService) : _service(service), _implService(implService)
{
assert(&service != &implService);
}
[[nodiscard]] std::string execute() const
{
return _service.action() + ", " + _implService.action() + " executed.";
}
};
int main()
{
ServiceProviderOptions options;
options.strongDestructionOrder = true;
options.prebuildSingletons = true;
options.checkServiceGlobalUniqueness = false;
ServiceProvider provider = ServiceCollection{}
.addSingleton<IService, Service>()
.addSingleton<Service>() // can be added one more time as separate service
// due to checkServiceGlobalUniqueness = false
.addScoped<ServiceExecutor>()
.buildServiceProvider(options);
const auto &executor = provider.getService<ServiceExecutor>();
std::cout << executor.execute();
return 0;
}
Output¶
Hello from service.