CodexBloom - Programming Q&A Platform

Unexpected Behavior When Using Dependency Injection with Multiple Implementations in .NET 6

πŸ‘€ Views: 76 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-22
ASP.NET Dependency Injection C#

I've searched everywhere and can't find a clear answer. I'm sure I'm missing something obvious here, but I'm facing an issue when trying to use dependency injection in my .NET 6 application. I have two implementations of a service interface, `IEmailService`, which sends emails using different providers. Here's the code for my service interface and implementations: ```csharp public interface IEmailService { void SendEmail(string recipient, string subject, string body); } public class SmtpEmailService : IEmailService { public void SendEmail(string recipient, string subject, string body) { // Logic to send email via SMTP } } public class SendGridEmailService : IEmailService { public void SendEmail(string recipient, string subject, string body) { // Logic to send email via SendGrid } } ``` In my `Startup.cs`, I register both implementations: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddScoped<IEmailService, SmtpEmailService>(); // Primary implementation services.AddScoped<IEmailService, SendGridEmailService>(); // Secondary implementation } ``` When I try to inject `IEmailService` into my `HomeController`, I expect to get the `SmtpEmailService`, but instead, I get an instance of `SendGridEmailService` every time. The behavior seems inconsistent depending on how I run the application (debug vs. release mode). Here’s how I'm injecting the service: ```csharp public class HomeController : Controller { private readonly IEmailService _emailService; public HomeController(IEmailService emailService) { _emailService = emailService; } public IActionResult Index() { _emailService.SendEmail("test@example.com", "Test Subject", "Test Body"); return View(); } } ``` I've also tried using named services and explicitly resolving the service using `IServiceProvider`, but that didn't help. I noticed that if I remove one of the registrations, the correct implementation is used as expected. Is there a best practice for handling multiple implementations of the same interface in .NET's DI container? Am I missing something in the configuration? Any insights would be greatly appreciated! For context: I'm using C# on Ubuntu. Am I missing something obvious? I'm working in a Ubuntu 20.04 environment. Any pointers in the right direction? I'm developing on Ubuntu 20.04 with C#.