Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 288
Jawad Al Shaikh Avatar asked Oct 04 '17 21:10

Jawad Al Shaikh


People also ask

What is IConfiguration in .NET core?

The IConfiguration is an interface for . Net Core 2.0. The IConfiguration interface need to be injected as dependency in the Controller and then later used throughout the Controller. The IConfiguration interface is used to read Settings and Connection Strings from AppSettings. json file.

What is scoped service in. net core?

In Asp.Net Core each request has in own service scope. Database and repository services are often registered as scoped services. Default registration of DbContext in EntityFramework Core is also scoped. Scoped lifetime ensures that all the services created within the request shares the same DbContext.

What is dependency injection in dot net core?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.


1 Answers

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.

like image 177
Federico Dipuma Avatar answered Nov 15 '22 17:11

Federico Dipuma