Reputation: 2735
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://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration
also by searching I couldn't find related content with accessing configuration! https://learn.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
Upvotes: 12
Views: 19037
Reputation: 139
I am not sure if it is needed.But we have appsettings.local.json and if we do not add this in program.cs, we can not read datas from appsetting.local.json.
so In program.cs we add ConfigureServices
statament in CreateWebHostBuilder
method at program.cs
var webHostBuilder = WebHost.CreateDefaultBuilder(args)
.UseApplicationInsights()
.ConfigureServices(services => services.AddSingleton<IConfiguration>(config))
.UseStartup<Startup>();
Upvotes: 0
Reputation: 18285
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.
Upvotes: 22