25#include <unordered_map>
46 template<
typename Interface,
typename Factory>
52 template<
typename Interface>
58 template<
typename Interface>
59 std::shared_ptr<Interface>
resolve();
64 template<
typename Interface>
71 virtual bool has_impl(std::type_index type)
const = 0;
74template<
typename Interface,
typename Factory>
77 std::function<std::shared_ptr<Interface>()>(std::forward<Factory>(factory)));
80template<
typename Interface>
85template<
typename Interface>
87 auto result =
resolve_impl(std::type_index(
typeid(Interface)));
88 if (result.has_value()) {
91 return std::any_cast<std::shared_ptr<Interface>>(result);
92 }
catch (
const std::bad_any_cast&) {
94 auto factory = std::any_cast<std::function<std::shared_ptr<Interface>()>>(result);
101template<
typename Interface>
103 return has_impl(std::type_index(
typeid(Interface)));
120 std::lock_guard<std::mutex> lock(
mutex_);
125 std::lock_guard<std::mutex> lock(
mutex_);
130 std::lock_guard<std::mutex> lock(
mutex_);
135 return singleton_it->second;
141 return factory_it->second;
147 bool has_impl(std::type_index type)
const override {
148 std::lock_guard<std::mutex> lock(
mutex_);
Interface for system bootstrapping.
virtual ~IBootstrapper()=default
virtual bool is_initialized() const =0
Check if the system is initialized.
virtual bool initialize()=0
Initialize the system.
virtual void shutdown()=0
Shutdown the system.
Abstract interface for dependency injection containers.
bool has() const
Check if a service is registered.
virtual std::any resolve_impl(std::type_index type)=0
Result< std::shared_ptr< TInterface > > resolve()
Resolve a service by its interface type.
virtual void register_singleton_impl(std::type_index type, std::any instance)=0
virtual void register_impl(std::type_index type, std::any factory)=0
virtual bool has_impl(std::type_index type) const =0
virtual ~IServiceContainer()=default
VoidResult register_factory(TFactory &&factory, service_lifetime lifetime=service_lifetime::singleton)
Register a factory function for creating service instances.
void register_singleton(std::shared_ptr< Interface > instance)
Register a singleton instance.
Simple thread-safe service container implementation.
void register_singleton_impl(std::type_index type, std::any instance) override
std::any resolve_impl(std::type_index type) override
bool has_impl(std::type_index type) const override
ServiceContainer()=default
void register_impl(std::type_index type, std::any factory) override
std::unordered_map< std::type_index, std::any > singletons_
std::unordered_map< std::type_index, std::any > factories_