Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an instance of IConfiguration locally?

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

like image 269
Joelty Avatar asked Jun 24 '19 08:06

Joelty


People also ask

How do I create an instance of IServiceProvider?

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.

How do I get IConfiguration in .NET core?

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.

How do you inject IConfiguration in net 6?

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); //... }


1 Answers

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

like image 198
Mustafa Gursel Avatar answered Sep 21 '22 13:09

Mustafa Gursel