I'd want to ask how to create an instance of ASP.NET Core's Configuration, the same that's being created when I require it in Controller's constructor which knows about the appsettings.json
file
like _config = ActivatorUtilities.CreateInstance<IConfiguration>(null);
System.InvalidOperationException: 'A suitable constructor for type 'Microsoft.Extensions.Configuration.IConfiguration' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.'
It makes sense because it is interface, but how it does work in Controller's Constructor case? and how can I create an instance of that?
I'm using MS DI
Thanks
An instance of IServiceProvider itself can be obtained by calling a BuildServiceProvider method of an IServiceCollection . IServiceCollection is a parameter of ConfigureServices method in a Startup class. It seems to be magically called with an instance of IServiceCollection by the framework.
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.
You could add the IConfiguration instance to the service collection as a singleton object in ConfigureServices : public void ConfigureServices(IServiceCollection service) { services. AddSingleton<IConfiguration>(Configuration); //... }
You can create a local instance of configuration as shown below.
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath([PATH_WHERE_appsettings.json_RESIDES])
.AddJsonFile("appsettings.json")
.Build();
For further information see Configuration in ASP.NET Core
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With