ASP.NET Core Interview Question #68
What is Replace in ASP.NET Core dependency injection?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
Replace removes the existing registration for a service type and adds a new ServiceDescriptor. It is useful when an application needs to replace a default registration supplied by a framework component or reusable library.
Detailed Explanation
Replace removes the existing registration for a service type and adds a new ServiceDescriptor. It is useful when an application needs to replace a default registration supplied by a framework component or reusable library.
For normal application code, explicit registration order or library extension points are often easier to understand. Replace is most useful when the existing registration must be deliberately substituted.
The replacement should use the correct lifetime so that it remains compatible with the consumers of the service.
Code Example
using Microsoft.Extensions.DependencyInjection.Extensions;
builder.Services.Replace(
ServiceDescriptor.Scoped<IEmailSender, CustomEmailSender>());