Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading