ASP.NET Core Dependency Injection 2 — Questions and Answers
Question 1: Which method retrieves a required service and throws if it is not registered?
- GetRequiredService<T>() (Correct answer)
- GetService<T>()
- Resolve<T>()
- Fetch<T>()
Correct answer: GetRequiredService<T>()
GetRequiredService<T>() throws InvalidOperationException if the service is not found, unlike GetService<T>() which returns null.
Question 2: How do you inject multiple implementations of the same interface in ASP.NET Core DI?
- Inject IEnumerable<TService> in the constructor (Correct answer)
- Register them under different names
- Use a factory method only
- Multiple implementations are not supported
Correct answer: Inject IEnumerable<TService> in the constructor
ASP.NET Core DI resolves all registered implementations of an interface when IEnumerable<TService> is injected.
Question 3: What is the purpose of the IServiceScope interface in ASP.NET Core?
- It creates a child DI scope for resolving scoped services outside a request (Correct answer)
- It defines service registration rules
- It limits the number of service instances
- It scopes logging to a component
Correct answer: It creates a child DI scope for resolving scoped services outside a request
IServiceScope provides a scoped IServiceProvider, used to resolve scoped services in background services or tests.
Question 4: Which DI registration method allows providing a factory function instead of a type?
- services.AddScoped<T>(sp => new T(...)) (Correct answer)
- services.UseFactory<T>()
- services.AddWithFactory<T>()
- services.RegisterFactory<T>()
Correct answer: services.AddScoped<T>(sp => new T(...))
The overload accepting Func<IServiceProvider, T> allows custom construction logic using the service provider.
Question 5: What is constructor injection in ASP.NET Core DI?
- Declaring dependencies as constructor parameters that the DI container resolves automatically (Correct answer)
- Manually creating service instances in constructors
- Injecting configuration into constructors only
- Using [Inject] attributes on constructors
Correct answer: Declaring dependencies as constructor parameters that the DI container resolves automatically
Constructor injection is the primary DI pattern where ASP.NET Core resolves and passes dependencies automatically when creating the class.
Question 6: What attribute enables property injection in ASP.NET Core Razor Pages?
- [BindProperty]
- [Inject]
- [FromServices] (Correct answer)
- [AutoInject]
Correct answer: [FromServices]
[FromServices] on a parameter or property tells the framework to resolve the value from the DI container rather than from the request.
Which method retrieves a required service and throws if it is not registered?