Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject IConfiguration into Program.cs (Console App) in .NET Core 3.0

I am trying to inject IConfiguration (Microsoft.Extensions.Configuration package) into Program.cs and don't know if that is possible and therefore obviously don't know how to do it, if possible.

I've done it in the Startup class in other projects, but there I just do a simple dependency injection, which I don't find to be done the same way in a console application.

The reason for it is, that I need to access some key values in the appsettings, in regards to access my database with the SqlConnection class (System.Data.SqlClient).

Normally, I just add it like this inside Startup.cs:

....
services.AddScoped(mysql => new SqlConnection($"and here goes my variables from appsettings..");
....

Do I need to use the Options pattern or is there a more simple way?

like image 834
badaboomskey Avatar asked Mar 26 '20 13:03

badaboomskey


People also ask

How do you inject IConfiguration in net core 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); //... }

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.


1 Answers

You would need to build the configuration yourself.

For example

static void  Main(string[] args) {

    var builder = new ConfigurationBuilder()
        //.SetBasePath("path here") //<--You would need to set the path
        .AddJsonFile("appsettings.json"); //or what ever file you have the settings

    IConfiguration configuration = builder.Build();

    //...use configuration as needed

}
like image 169
Nkosi Avatar answered Sep 20 '22 10:09

Nkosi