
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?
回答
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?
回答
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?
回答
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 面接問題