Search code examples
c#.netasp.net-mvcasp.net-coredependency-injection

Inconsistent Service Dependency References with ASP .NET Core DI


I'm working on an ASP .NET Core app with a DI setup, and I've encountered an issue related to dependency references that are not behaving as expected.

I have a series of services and interfaces that use Singleton registration in the DI container. Specifically, I have a WeatherService and a child class CurrentWeatherService that inherits from WeatherService. Both services are registered as Singletons.

Here's the simplified setup in my program:

services.AddSingleton<IWeatherService, WeatherService>();
services.AddSingleton<ICurrentWeatherService, CurrentWeatherService>();

Now, when I access WeatherService directly and also via CurrentWeatherService using the base keyword, I notice that they are not referencing the same instance, despite being registered as Singleton. What might be causing this issue? I would like them to share the same instance.

Here's the basic structure of my classes:

public class WeatherService : IWeatherService
{
    /******/
    
    protected virtual async Task<T> GetWeatherDataAsync<T>(string endpoint) where T : class
    {
        /******/
    }
}

public class CurrentWeatherService : WeatherService, ICurrentWeatherService
{
    /******/
    
    protected override async Task<T> GetWeatherDataAsync<T>(string endpoint)
    {
        return await base.GetWeatherDataAsync<T>(endpoint);
    }
}

Is there something in my Dependency Injection setup that I might be missing or any known .NET Core behaviour that could explain this?

Any insights or suggestions would be greatly appreciated.


Solution

  • You don't use DI. Instead you use inheritance. To use DI you should rewrite your current weather service implementation:

    public class CurrentWeatherService : ICurrentWeatherService
    {
        private readonly IWeatherService _weatherService;
    
        public CurrentWeatherService(IWeatherService weatherService)
        {
            _weatherService = weatherService
                ?? throw new ArgumentNullException(nameof(weatherService));
        }
    
        public async Task<T> GetWeatherDataAsync<T>(string endpoint)
        {
            return await _weatherService.GetWeatherDataAsync<T>(endpoint);
        }
    }