This repository demonstrates Dependency Injection (DI) lifetimes in ASP.NET Core using a simplified, Microsoft-recommended approach. The architecture focuses on clarity and educational value.
- Simplicity First: Following Microsoft's documentation patterns for clear understanding
- Single Responsibility: Each component has one clear purpose
- Observable Behavior: Using GUIDs to make instance creation visible
- Minimal Complexity: No unnecessary abstractions or patterns
- IOperation: Base interface with
OperationIdproperty - IOperationTransient: Marker interface for transient lifetime
- IOperationScoped: Marker interface for scoped lifetime
- IOperationSingleton: Marker interface for singleton lifetime
- Single class implementing all three lifetime interfaces
- Generates unique GUID on instantiation
- Makes instance creation observable
- Depends on all three lifetime variants
- Demonstrates how different lifetimes interact
- Provides snapshot functionality for easy comparison
- Three endpoints demonstrating different aspects:
/api/Operations: Complete comparison/api/Operations/simple: Basic lifetime tracking/api/Operations/multiple: Multiple injections per request
- Creation: New instance every time it's requested
- Use Case: Lightweight, stateless services
- Example: Utility services, calculators
- Creation: One instance per HTTP request
- Use Case: Request-specific state
- Example: Database contexts, unit of work
- Creation: One instance for entire application lifetime
- Use Case: Shared state, expensive resources
- Example: Configuration, caches
// Clear, explicit registration showing lifetime differences
builder.Services.AddTransient<IOperationTransient, Operation>();
builder.Services.AddScoped<IOperationScoped, Operation>();
builder.Services.AddSingleton<IOperationSingleton, Operation>();- Same Implementation, Different Lifetimes: Shows how lifetime is about registration, not implementation
- Observable Differences: GUIDs make instance creation visible
- Real-World Patterns: Demonstrates practical usage scenarios
- No Magic: Everything is explicit and traceable
- Interface Segregation: Separate interfaces for different lifetimes
- Dependency Injection: Constructor injection throughout
- Testability: All dependencies are injected
- Clear Naming: Intent is obvious from names
- No Captive Dependencies: No scoped services in singletons
- No Service Locator: Pure dependency injection
- No Hidden State: All state is explicit
- Thread Safety: Singleton is immutable
This architecture is optimized for:
- Learning: Clear demonstration of concepts
- Teaching: Easy to explain and understand
- Experimentation: Simple to modify and test
- Reference: Clean example of DI patterns