ASP.NET Core Interview Question #63
How do you register an interface and implementation in ASP.NET Core DI?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
The common registration form maps an abstraction to a concrete implementation using AddTransient, AddScoped, or AddSingleton.
Detailed Explanation
The common registration form maps an abstraction to a concrete implementation using AddTransient, AddScoped, or AddSingleton.
When a consumer requests the interface, the container creates or returns the configured implementation according to its lifetime. Registering against interfaces can reduce coupling and make testing or implementation replacement easier.
An interface is not mandatory for every class. Concrete types can also be registered directly when an abstraction does not add useful value.
Code Example
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IProductService, ProductService>();
public ProductService(IProductRepository repository)
{
_repository = repository;
}