using Inversion; using Invercargill; /** * Lifecycle Demo Example * * This example demonstrates the three different lifecycles in Inversion: * - TRANSIENT: New instance each time * - SCOPED: One instance per scope * - SINGLETON: One instance for the entire container */ public class LifecycleDemo : Object { // A counter service to track instance creation public class Counter : Object { private static int total_created = 0; private int instance_id; public Counter() { total_created++; this.instance_id = total_created; stdout.printf(" Counter #%d created\n", this.instance_id); } public int id { get { return this.instance_id; } } } public static int main(string[] args) { stdout.printf("=== Inversion IoC Lifecycle Demo ===\n\n"); var container = new Container(); // Register three counters with different lifecycles container.register_transient((scope) => new Counter()); stdout.printf("Registered Counter as TRANSIENT\n"); container.register_scoped((scope) => new Counter()); stdout.printf("Registered Counter as SCOPED\n"); container.register_singleton((scope) => new Counter()); stdout.printf("Registered Counter as SINGLETON\n\n"); // Note: In a real scenario, you'd register different types. // For this demo, we'll show the lifecycle concepts. // Demonstrate SINGLETON behavior stdout.printf("--- SINGLETON Demo ---\n"); var scope1 = container.create_scope(); var scope2 = container.create_scope(); // Create first scope stdout.printf("Creating scope 1:\n"); // Demonstrate TRANSIENT behavior stdout.printf("\n--- TRANSIENT Demo ---\n"); stdout.printf("Resolving transient three times:\n"); // Since all registrations are for Counter, resolve_all gets all of them // Let's demonstrate by resolving multiple times try { var all_counters = scope1.resolve_all(); stdout.printf("\nResolved all counters (3 different registrations):\n"); all_counters.iterate((obj) => { var counter = (Counter) obj; stdout.printf(" Got Counter #%d\n", counter.id); }); } catch (Error e) { stderr.printf("Error: %s\n", e.message); } stdout.printf("\n--- SCOPED Demo ---\n"); stdout.printf("Creating another scope and resolving:\n"); var scope3 = container.create_scope(); try { var counters = scope3.resolve_all(); stdout.printf("Resolved in another scope:\n"); counters.iterate((obj) => { var counter = (Counter) obj; stdout.printf(" Got Counter #%d\n", counter.id); }); } catch (Error e) { stderr.printf("Error: %s\n", e.message); } stdout.printf("\n=== Lifecycle Demo Complete ===\n"); return 0; } }