
Dependency Injection
Service lifetimes (singleton, scoped, transient), service registration, IServiceProvider, best practices
1What is the main difference between Singleton, Scoped, and Transient lifetimes?
What is the main difference between Singleton, Scoped, and Transient lifetimes?
Risposta
Singleton creates a single instance for the entire application lifetime, Scoped creates one instance per HTTP request (or scope), and Transient creates a new instance every time it's injected. These lifetimes determine when and how many times the DI container instantiates a service. Use Singleton for stateless shared services, Scoped for request-bound services (like DbContext), and Transient for lightweight stateless services.
2Which lifetime should be used to register an Entity Framework Core DbContext?
Which lifetime should be used to register an Entity Framework Core DbContext?
Risposta
DbContext should be registered with Scoped lifetime because it's not thread-safe and maintains entity tracking state. Each HTTP request should have its own DbContext instance to avoid concurrency issues. Registration is done with AddDbContext which automatically configures Scoped lifetime. Using Singleton would cause concurrency errors, and Transient would waste resources by creating too many instances.
3How to register a service with an interface and its implementation?
How to register a service with an interface and its implementation?
Risposta
Service registration is done with AddSingleton, AddScoped, or AddTransient methods by specifying the interface as the service type and the concrete class as the implementation. The syntax is services.Add{Lifetime}<IInterface, Implementation>(). This approach respects the dependency inversion principle and facilitates testing by allowing implementation substitution. The DI container will automatically resolve the concrete implementation when injecting the interface.
When should AddSingleton be preferred over AddScoped?
What is the role of IServiceProvider in the DI system?
+21 domande da colloquio
Altri argomenti di colloquio .NET
C# Basics
LINQ & Delegates
C# Language Essentials
ASP.NET Core Fundamentals
ASP.NET Core Request Lifecycle
Configuration & Settings
Application Lifecycle
Entity Framework Core
Minimal APIs
Web API Development
Async in ASP.NET Core
Authentication & Authorization
HttpClient & Networking
JSON Serialization
Entity Framework Core Advanced
C# Advanced Features
Clean Architecture
Logging, Monitoring & Observability
Unit Testing & xUnit
Integration Testing
Docker & Containerization
NuGet Package Management
Memory Management & GC
Reactive Programming
Async/await & Patterns
.NET Design Patterns
Performance Optimization
Security & Best Practices
SignalR & Real-time
Microservices Architecture
Padroneggia .NET per il tuo prossimo colloquio
Accedi a tutte le domande, flashcards, test tecnici, esercizi di code review e simulatori di colloquio.
Inizia gratis