ASP.NET Core Interview Question #67
What is TryAdd in ASP.NET Core dependency injection?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
TryAdd extension methods register a service only when that service type has not already been registered. They are provided by Microsoft.Extensions.DependencyInjection.Extensions.
Detailed Explanation
TryAdd extension methods register a service only when that service type has not already been registered. They are provided by Microsoft.Extensions.DependencyInjection.Extensions.
TryAdd is particularly useful in reusable libraries because it provides a default implementation while allowing an application to register its own implementation first.
Related methods include TryAddTransient, TryAddScoped, TryAddSingleton, and TryAddEnumerable for scenarios involving multiple registrations.
Code Example
using Microsoft.Extensions.DependencyInjection.Extensions;
builder.Services.TryAddScoped<IEmailSender, DefaultEmailSender>();