Common System 0.2.0
Common interfaces and patterns for system integration
Loading...
Searching...
No Matches
service_container_example.cpp File Reference
#include <kcenon/common/di/service_container.h>
#include <kcenon/common/patterns/result.h>
#include <iostream>
#include <memory>
#include <string>
Include dependency graph for service_container_example.cpp:

Go to the source code of this file.

Classes

class  IGreeter
 
class  ICounter
 
class  FriendlyGreeter
 
class  SequentialCounter
 

Functions

int main ()
 

Function Documentation

◆ main()

int main ( )

Definition at line 61 of file service_container_example.cpp.

62{
63 std::cout << "=== Service Container Example ===\n\n";
64
65 auto& container = service_container::global();
66 container.clear();
67
68 // Register a singleton greeter (one instance shared)
69 std::cout << "1. Registering services...\n";
70 container.register_factory<IGreeter>(
71 [](IServiceContainer&) { return std::make_shared<FriendlyGreeter>(); },
72 service_lifetime::singleton);
73
74 // Register a transient counter (new instance each time)
75 container.register_factory<ICounter>(
76 [](IServiceContainer&) { return std::make_shared<SequentialCounter>(); },
77 service_lifetime::transient);
78
79 // Resolve services
80 std::cout << "2. Resolving services...\n";
81 auto greeter = container.resolve<IGreeter>();
82 if (greeter.is_ok())
83 {
84 std::cout << " " << greeter.value()->greet("Developer") << "\n";
85 }
86
87 // Singleton: same instance
88 auto greeter2 = container.resolve<IGreeter>();
89 std::cout << "3. Singleton check: same instance = "
90 << (greeter.value().get() == greeter2.value().get() ? "true" : "false")
91 << "\n";
92
93 // Transient: different instances
94 auto counter1 = container.resolve<ICounter>();
95 auto counter2 = container.resolve<ICounter>();
96 std::cout << "4. Transient check: counter1=" << counter1.value()->next()
97 << ", counter2=" << counter2.value()->next() << "\n";
98
99 // Scoped container
100 std::cout << "5. Creating scoped container...\n";
101 auto scope = container.create_scope();
102 if (scope)
103 {
104 std::cout << " Scope created successfully\n";
105 }
106
107 // Freeze container (prevent further registrations)
108 std::cout << "6. Freezing container for production...\n";
109 container.freeze();
110 std::cout << " Frozen = " << (container.is_frozen() ? "true" : "false") << "\n";
111
112 // List registered services
113 auto services = container.registered_services();
114 std::cout << "7. Registered services: " << services.size() << "\n";
115
116 container.clear();
117 std::cout << "\nDone.\n";
118 return 0;
119}
virtual int next()=0
Abstract interface for dependency injection containers.
Definition di.cppm:39
static service_container & global()
Get the global service container instance.

References kcenon::common::di::service_container::global(), and ICounter::next().

Here is the call graph for this function: