Common System 0.2.0
Common interfaces and patterns for system integration
Loading...
Searching...
No Matches
service_container_interface.h
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
26#pragma once
27
28#include <any>
29#include <concepts>
30#include <functional>
31#include <memory>
32#include <string>
33#include <typeindex>
34#include <vector>
35
36#include "../patterns/result.h"
37#include "../concepts/service.h"
39
40namespace kcenon::common {
41namespace di {
42
52enum class service_lifetime {
64
75
86 scoped
87};
88
94inline const char* to_string(service_lifetime lifetime) {
95 switch (lifetime) {
96 case service_lifetime::singleton: return "singleton";
97 case service_lifetime::transient: return "transient";
98 case service_lifetime::scoped: return "scoped";
99 default: return "unknown";
100 }
101}
102
112 std::type_index interface_type;
113
115 std::string interface_name;
116
119
121 bool is_instantiated = false;
122
124 std::string description;
125
126 service_descriptor(std::type_index type, std::string name, service_lifetime lt)
127 : interface_type(type)
128 , interface_name(std::move(name))
129 , lifetime(lt) {}
130};
131
132// Forward declaration
133class IServiceScope;
134
183class IServiceContainer {
184public:
185 virtual ~IServiceContainer() = default;
186
187 // ===== Service Registration (Type-safe templates) =====
188
205 template<concepts::ServiceInterface TInterface,
208
210 std::type_index(typeid(TInterface)),
211 typeid(TInterface).name(),
212 [](IServiceContainer&) -> std::shared_ptr<void> {
213 return std::make_shared<TImpl>();
214 },
215 lifetime
216 );
217 }
218
229 template<typename TInterface>
230 VoidResult register_instance(std::shared_ptr<TInterface> instance) {
231 if (!instance) {
234 "Cannot register null instance",
235 "di::IServiceContainer"
236 );
237 }
238
240 std::type_index(typeid(TInterface)),
241 typeid(TInterface).name(),
242 std::static_pointer_cast<void>(instance)
243 );
244 }
245
261 template<concepts::ServiceInterface TInterface,
263 VoidResult register_factory(TFactory&& factory,
266 std::type_index(typeid(TInterface)),
267 typeid(TInterface).name(),
268 [f = std::forward<TFactory>(factory)](IServiceContainer& c) -> std::shared_ptr<void> {
269 return std::static_pointer_cast<void>(f(c));
270 },
271 lifetime
272 );
273 }
274
288 template<concepts::ServiceInterface TInterface,
293 std::type_index(typeid(TInterface)),
294 typeid(TInterface).name(),
295 [f = std::forward<TFactory>(factory)](IServiceContainer&) -> std::shared_ptr<void> {
296 return std::static_pointer_cast<void>(f());
297 },
298 lifetime
299 );
300 }
301
302 // ===== Service Resolution =====
303
319 template<typename TInterface>
321 auto result = resolve_internal(std::type_index(typeid(TInterface)));
322
323 if (result.is_err()) {
324 return make_error<std::shared_ptr<TInterface>>(result.error());
325 }
326
328 std::static_pointer_cast<TInterface>(result.value())
329 );
330 }
331
341 template<typename TInterface>
342 std::shared_ptr<TInterface> resolve_or_null() {
343 auto result = resolve<TInterface>();
344 if (result.is_ok()) {
345 return result.value();
346 }
347 return nullptr;
348 }
349
350 // ===== Scope Management =====
351
360 virtual std::unique_ptr<IServiceScope> create_scope() = 0;
361
362 // ===== Introspection =====
363
370 template<typename TInterface>
371 bool is_registered() const {
372 return is_registered_internal(std::type_index(typeid(TInterface)));
373 }
374
380 virtual std::vector<service_descriptor> registered_services() const = 0;
381
391 template<typename TInterface>
393 return unregister_internal(std::type_index(typeid(TInterface)));
394 }
395
404 virtual VoidResult clear() = 0;
405
406protected:
407 // Internal type-erased methods for implementation
408
413 std::type_index interface_type,
414 const std::string& type_name,
415 std::function<std::shared_ptr<void>(IServiceContainer&)> factory,
416 service_lifetime lifetime) = 0;
417
422 std::type_index interface_type,
423 const std::string& type_name,
424 std::shared_ptr<void> instance) = 0;
425
430 std::type_index interface_type) = 0;
431
435 virtual bool is_registered_internal(std::type_index interface_type) const = 0;
436
440 virtual VoidResult unregister_internal(std::type_index interface_type) = 0;
441};
442
470public:
471 ~IServiceScope() override = default;
472
477 virtual IServiceContainer& parent() = 0;
478
483 virtual const IServiceContainer& parent() const = 0;
484};
485
512
513} // namespace di
514} // namespace kcenon::common
Result type for error handling with member function support.
Definition core.cppm:165
Abstract interface for dependency injection containers.
Definition di.cppm:39
bool is_registered() const
Check if a service type is registered.
std::shared_ptr< TInterface > resolve_or_null()
Try to resolve a service, returning nullptr if not found.
VoidResult register_simple_factory(TFactory &&factory, service_lifetime lifetime=service_lifetime::singleton)
Register a simple factory function without container access.
virtual Result< std::shared_ptr< void > > resolve_internal(std::type_index interface_type)=0
Internal service resolution (type-erased).
virtual std::unique_ptr< IServiceScope > create_scope()=0
Create a new service scope.
Result< std::shared_ptr< TInterface > > resolve()
Resolve a service by its interface type.
virtual VoidResult register_instance_internal(std::type_index interface_type, const std::string &type_name, std::shared_ptr< void > instance)=0
Internal instance registration (type-erased).
VoidResult register_type(service_lifetime lifetime=service_lifetime::singleton)
Register a service type with its implementation.
virtual VoidResult unregister_internal(std::type_index interface_type)=0
Internal unregistration (type-erased).
virtual std::vector< service_descriptor > registered_services() const =0
Get list of all registered service descriptors.
virtual bool is_registered_internal(std::type_index interface_type) const =0
Internal registration check (type-erased).
VoidResult register_instance(std::shared_ptr< TInterface > instance)
Register a pre-existing instance as a singleton.
VoidResult unregister()
Unregister a service type.
virtual VoidResult clear()=0
Clear all registrations.
virtual VoidResult register_factory_internal(std::type_index interface_type, const std::string &type_name, std::function< std::shared_ptr< void >(IServiceContainer &)> factory, service_lifetime lifetime)=0
Internal factory registration (type-erased).
VoidResult register_factory(TFactory &&factory, service_lifetime lifetime=service_lifetime::singleton)
Register a factory function for creating service instances.
Scoped service container for request-level isolation.
virtual const IServiceContainer & parent() const =0
Get the parent container (const).
virtual IServiceContainer & parent()=0
Get the parent container.
~IServiceScope() override=default
A callable that creates service instances.
Definition service.h:98
A type that implements a service interface.
Definition service.h:77
A type that can be used as a service interface.
Definition service.h:58
A callable that creates service instances without container access.
Definition service.h:118
Centralized error code registry for all systems.
constexpr int scoped_from_root
Scoped service resolved from root container.
constexpr int circular_dependency
Circular dependency detected during resolution.
constexpr int invalid_lifetime
Invalid service lifetime configuration.
constexpr int factory_error
Factory threw an exception during instantiation.
constexpr int service_not_registered
Service not registered in container.
constexpr int already_registered
Service already registered (duplicate registration attempt)
const char * to_string(service_lifetime lifetime)
Convert service_lifetime to string representation.
service_lifetime
Defines the lifetime policy for registered services.
@ singleton
Single instance shared globally.
@ scoped
Single instance within a scope.
@ transient
New instance created for each request.
constexpr int INVALID_ARGUMENT
Definition compat.h:31
Core interfaces.
Definition adapter.h:21
Result< T > make_error(int code, const std::string &message, const std::string &module="")
Create an error result with code and message.
Definition utilities.h:91
VoidResult ok()
Create a successful void result.
Definition utilities.h:71
Umbrella header for Result<T> type and related utilities.
C++20 concepts for dependency injection and service container.
Metadata describing a registered service.
service_descriptor(std::type_index type, std::string name, service_lifetime lt)
std::type_index interface_type
Type index of the interface being registered.
bool is_instantiated
Whether this service has been instantiated (for singletons)
service_lifetime lifetime
Lifetime policy for this service.
std::string description
Optional description or tags for the service.
std::string interface_name
Human-readable name of the interface type.