15#include <unordered_map>
46 template<
typename Interface,
typename Implementation>
48 static_assert(std::is_base_of_v<Interface, Implementation>,
49 "Implementation must derive from Interface");
51 std::lock_guard<std::mutex> lock(
mutex_);
52 services_[std::type_index(
typeid(Interface))] =
62 template<
typename Interface>
65 std::lock_guard<std::mutex> lock(
mutex_);
66 services_[std::type_index(
typeid(Interface))] =
68 [factory]() -> std::shared_ptr<void> {
79 template<
typename Interface,
typename Implementation,
typename... Args>
81 static_assert(std::is_base_of_v<Interface, Implementation>,
82 "Implementation must derive from Interface");
85 []() {
return std::make_shared<Implementation>(); },
94 template<
typename Interface>
96 std::lock_guard<std::mutex> lock(
mutex_);
98 auto it =
services_.find(std::type_index(
typeid(Interface)));
103 auto& entry = it->second;
107 return std::static_pointer_cast<Interface>(entry.instance);
112 auto instance = entry.factory();
116 entry.instance = instance;
119 return std::static_pointer_cast<Interface>(instance);
130 template<
typename Interface>
132 std::lock_guard<std::mutex> lock(
mutex_);
140 std::lock_guard<std::mutex> lock(
mutex_);
157 std::function<std::shared_ptr<void>()>
factory;
161 std::unordered_map<std::type_index, service_entry>
services_;
167template<
typename Interface>
RAII helper for scoped service registration.
scoped_service(std::shared_ptr< Interface > service)
Modern service container for dependency injection.
void register_singleton(std::shared_ptr< Implementation > instance)
Register a service with singleton lifetime.
void clear()
Clear all registered services.
lifetime
Service lifetime scope.
static service_container & global()
Get the global service container instance.
bool is_registered() const
Check if a service is registered.
std::shared_ptr< Interface > resolve()
Resolve a service.
void register_factory(std::function< std::shared_ptr< Interface >()> factory, lifetime lt=lifetime::transient)
Register a service with factory function.
void register_transient()
Register a transient service.
std::unordered_map< std::type_index, service_entry > services_
Core threading foundation of the thread system library.
std::shared_ptr< void > instance
std::function< std::shared_ptr< void >()> factory