CodexBloom - Programming Q&A Platform

Confusion with Interface Implementation for Dependency Injection in ASP.NET Core 6

👀 Views: 65 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
asp.net-core dependency-injection httpclient C#

I'm working with an scenario with implementing an interface for dependency injection in my ASP.NET Core 6 application. I have an interface `IWeatherService` that I want to use for fetching weather data. My implementation of this interface is `WeatherService`, which uses `HttpClient` to call an external weather API. When I try to inject this service into my controller, I'm getting a `System.InvalidOperationException: Unable to resolve service for type 'MyApp.Services.IWeatherService' while attempting to activate 'MyApp.Controllers.WeatherController'`. Here's a simplified version of my `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddHttpClient(); services.AddScoped<IWeatherService, WeatherService>(); } ``` And my `WeatherService` implementation looks like this: ```csharp public class WeatherService : IWeatherService { private readonly HttpClient _httpClient; public WeatherService(HttpClient httpClient) { _httpClient = httpClient; } public async Task<string> GetWeatherAsync(string city) { var response = await _httpClient.GetAsync($"https://api.weather.com/v3/weather/{city}"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } ``` And my controller: ```csharp [ApiController] [Route("api/[controller]")] public class WeatherController : ControllerBase { private readonly IWeatherService _weatherService; public WeatherController(IWeatherService weatherService) { _weatherService = weatherService; } [HttpGet("{city}")] public async Task<IActionResult> GetWeather(string city) { var weather = await _weatherService.GetWeatherAsync(city); return Ok(weather); } } ``` I've made sure to check that both the service and controller are in the same assembly and the namespaces are correct. I've also tried restarting the application and cleaning the solution, but the behavior continues. What am I missing here?