Is services.AddSingleton<IConfiguration> really needed in .net core 2 API

11,403

As the official roadmap for ASP.NET Core 2.0 says:

An IConfiguration instance will be added to the services container by default in ASP.NET Core 2.0, so that all applications can easily retrieve configuration values via the container

So services.AddSingleton<IConfiguration> (or similar) is already called by the framework itself.

You may see this behavior inside WebHostBuilder.cs file or (when using the utility extension methods) inside HostBuilder.cs file.

Share:
11,403
Jawad Al Shaikh
Author by

Jawad Al Shaikh

Just another minimalist practicing development in IT domain. #OpenToWork

Updated on June 05, 2022

Comments

  • Jawad Al Shaikh
    Jawad Al Shaikh almost 2 years

    I accessed appsettings.json In .NET Core 2 Web API Controller simply by adding below:

    public class MyController : Controller
        {
            private readonly IConfiguration appConfig;
    
            public MyController(IConfiguration configuration)
            {
                appConfig = configuration;
            }
        }
    

    Without adding below in Startup class ConfigureServices(IServiceCollection services) after services.AddMvc();:

    services.AddSingleton<IConfiguration>(Configuration);
    

    Is there any flaws in my approach? In official docs for .Net Core 2 configuration section, its not mentioned to use 'AddSingleton' not even once: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration

    also by searching I couldn't find related content with accessing configuration! https://docs.microsoft.com/en-us/search/index?search=AddSingleton&scope=ASP.NET+Core

    Links below shows AddSingleton as if mandatory step:

    Access appsettings.json values in controller classes

    https://blogs.technet.microsoft.com/dariuszporowski/tip-of-the-week-how-to-access-configuration-from-controller-in-asp-net-core-2-0/

  • Jawad Al Shaikh
    Jawad Al Shaikh over 6 years
    So what happens when user adding it manually beside its being set by default? it seems no warns or errors appeared!
  • Federico Dipuma
    Federico Dipuma over 6 years
    As with any other registration in ASP.NET Core DI, the last registration is used whenever anyone requests that service from the IServiceProvider. Because, in your case, the registration is the same, nothing changes (you have now two identical registrations for the same service).
  • GvSharma
    GvSharma over 3 years
    AddSingleton is not accessible
  • Died
    Died over 2 years
    On VS2022 preview 4.1, builder.Services.AddSingleton<IConfiguration>(builder.Config‌​uration); will cause System.StackOverflowException. So this line should be remove.