| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- 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<Counter>((scope) => new Counter());
- stdout.printf("Registered Counter as TRANSIENT\n");
- container.register_scoped<Counter>((scope) => new Counter());
- stdout.printf("Registered Counter as SCOPED\n");
- container.register_singleton<Counter>((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<Counter>();
- 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<Counter>();
- 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;
- }
- }
|