ASP.NET Core Dependency Injection 1 — Questions and Answers
Question 1: Which service lifetime registers a new instance for every HTTP request in ASP.NET Core?
- Scoped (Correct answer)
- Singleton
- Transient
- PerRequest
Correct answer: Scoped
Scoped services are created once per HTTP request and shared within that request's scope.
Question 2: What happens when a Singleton service depends on a Scoped service in ASP.NET Core?
- It causes a captive dependency anti-pattern and may throw an exception (Correct answer)
- The scoped service becomes singleton automatically
- ASP.NET Core handles it transparently
- The singleton is downgraded to scoped
Correct answer: It causes a captive dependency anti-pattern and may throw an exception
Injecting a shorter-lived scoped service into a singleton creates a captive dependency; with scope validation enabled, it throws at startup.
Question 3: Which method registers a service with Transient lifetime in ASP.NET Core DI?
- services.AddTransient<TService, TImplementation>() (Correct answer)
- services.RegisterTransient<TService>()
- services.UseTransient<TService>()
- services.BindTransient<TService>()
Correct answer: services.AddTransient<TService, TImplementation>()
AddTransient<TService, TImplementation>() registers the implementation to be created fresh each time it is requested.
Question 4: What interface is used to access the DI service container manually in ASP.NET Core?
- IServiceProvider (Correct answer)
- IServiceContainer
- IDependencyResolver
- IServiceLocator
Correct answer: IServiceProvider
IServiceProvider exposes the GetService and GetRequiredService methods to resolve dependencies from the container.
Question 5: Which ASP.NET Core method is used to register all services with the DI container?
- ConfigureServices() in Startup or builder.Services in Program.cs (Correct answer)
- Configure() in Startup
- RegisterServices() in Program.cs
- SetupDI() in appsettings.json
Correct answer: ConfigureServices() in Startup or builder.Services in Program.cs
Services are registered in ConfigureServices() (classic Startup) or via builder.Services in the minimal hosting model.
Question 6: What does services.AddScoped<IService, ServiceImpl>() do?
- Registers ServiceImpl as the implementation for IService with scoped lifetime (Correct answer)
- Adds a singleton implementation
- Creates a new DI scope
- Registers only the interface without implementation
Correct answer: Registers ServiceImpl as the implementation for IService with scoped lifetime
This registers ServiceImpl to be resolved whenever IService is requested, creating one instance per scope.
Which service lifetime registers a new instance for every HTTP request in ASP.NET Core?