Demonstrates DI service container with singleton, transient, and scoped lifetimes.
Demonstrates DI service container with singleton, transient, and scoped lifetimes.Shows service registration with factory functions, resolution, scoped containers, and container freezing for production safety.
#include <iostream>
#include <memory>
#include <string>
{
public:
virtual std::string
greet(
const std::string& name)
const = 0;
};
{
public:
};
{
public:
std::string
greet(
const std::string& name)
const override
{
return "Hello, " + name + "! Welcome aboard.";
}
};
{
public:
private:
};
{
std::cout << "=== Service Container Example ===\n\n";
auto& container = service_container::global();
container.clear();
std::cout << "1. Registering services...\n";
service_lifetime::singleton);
service_lifetime::transient);
std::cout << "2. Resolving services...\n";
auto greeter = container.resolve<
IGreeter>();
if (greeter.is_ok())
{
std::cout << " " << greeter.value()->greet("Developer") << "\n";
}
auto greeter2 = container.resolve<
IGreeter>();
std::cout << "3. Singleton check: same instance = "
<< (greeter.value().get() == greeter2.value().get() ? "true" : "false")
<< "\n";
auto counter1 = container.resolve<
ICounter>();
auto counter2 = container.resolve<
ICounter>();
std::cout <<
"4. Transient check: counter1=" << counter1.value()->
next()
<<
", counter2=" << counter2.value()->
next() <<
"\n";
std::cout << "5. Creating scoped container...\n";
auto scope = container.create_scope();
if (scope)
{
std::cout << " Scope created successfully\n";
}
std::cout << "6. Freezing container for production...\n";
container.freeze();
std::cout << " Frozen = " << (container.is_frozen() ? "true" : "false") << "\n";
auto services = container.registered_services();
std::cout << "7. Registered services: " << services.size() << "\n";
container.clear();
std::cout << "\nDone.\n";
return 0;
}
std::string greet(const std::string &name) const override
virtual ~ICounter()=default
virtual ~IGreeter()=default
virtual std::string greet(const std::string &name) const =0
Abstract interface for dependency injection containers.
Umbrella header for Result<T> type and related utilities.
Implementation of the service container for dependency injection.