Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 6 how to access Configuration during setup

In earlier versions, we had Startup.cs class and we get configuration object as follows in the Startup file.

public class Startup 
{
    private readonly IHostEnvironment environment;
    private readonly IConfiguration config;

    public Startup(IConfiguration configuration, IHostEnvironment environment) 
    {
        this.config = configuration;
        this.environment = environment;
    }

    public void ConfigureServices(IServiceCollection services) 
    {
        // Add Services
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
    {
        // Add Middlewares
    }

}

Now in .NET 6 (With Visual Studio 2022), we don't see the Startup.cs class. Looks like its days are numbered. So how do we get these objects like Configuration(IConfiguration) and Hosting Environment(IHostEnvironment)

How do we get these objects, to say read the configuration from appsettings? Currently the Program.cs file looks like this.

using Festify.Database;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<FestifyContext>();


////////////////////////////////////////////////
// The following is Giving me error as Configuration 
// object is not avaible, I dont know how to inject this here.
////////////////////////////////////////////////


builder.Services.AddDbContext<FestifyContext>(opt =>
        opt.UseSqlServer(
            Configuration.GetConnectionString("Festify")));


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

I want to know how to read the configuration from appsettings.json ?

like image 298
VivekDev Avatar asked Oct 26 '21 12:10

VivekDev


People also ask

Where is configuration information in ASP.NET Core?

In ASP.NET Core application, the configuration is stored in name-value pairs and it can be read at runtime from various parts of the application. The name-value pairs may be grouped into multi-level hierarchy.

Does ASP.NET Core have web config?

The web. config file has also been replaced in ASP.NET Core. Configuration itself can now be configured, as part of the application startup procedure described in Startup.

Can you use app config in .NET Core?

Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.


5 Answers

WebApplicationBuilder returned by WebApplication.CreateBuilder(args) exposes Configuration and Environment properties:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration; // allows both to access and to set up the config
IWebHostEnvironment environment = builder.Environment;

WebApplication returned by WebApplicationBuilder.Build() also exposes Configuration and Environment:

var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;

Also check the migration guide and code samples.

like image 155
Guru Stron Avatar answered Oct 07 '22 16:10

Guru Stron


In Program.cs, the WebApplicationBuilder is created shown below.

var builder = WebApplication.CreateBuilder(args);

Once we have the builder created, the configuration is available.

Let's assume you have the default appSettings.json in place. The example code below would return the configuration Default log level setting from the JSON configuration file.

builder.Configuration["Logging:LogLevel:Default"] // returns "Warning"

Once the app is running, you can access the Configuration settings via dependency injection in other classes of your application.

public MyClass(IConfiguration configuration)
{
   var logLevel = configuration["Logging:LogLevel:Default"];
}

A nice feature worth considering it to create a class that represents your settings and then bind the configuration to an instance of that class type. For example, let's assume you create a new class called MyAppSettings with the same structure as your appSettings.json, you can do the following:

var myAppSettings = builder.Configuration.Get<MyAppSettings>();
string logLevel = myAppSettings.Logging.LogLevel.Default;
like image 23
James Lawruk Avatar answered Oct 07 '22 15:10

James Lawruk


.NET 6 already gives builder object in Program.cs

var builder = WebApplication.CreateBuilder(args);

Just use this builder to access configuration and Environment as an example to get ConnectionString from app.settings.cs as follows:

builder.Services.AddDbContext<DataContext>( options =>
{
  options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectiion"));
});
like image 33
Varun Tripathi Avatar answered Oct 07 '22 17:10

Varun Tripathi


All you need is to add "builder." before your Configuration

Like:

builder.Services
       .AddDbContext<FestifyContext>
    (opt =>opt.UseSqlServer(builder.Configuration
                                   .GetConnectionString("Festify")));

like image 6
Furqan Mestri Avatar answered Oct 07 '22 16:10

Furqan Mestri


//.NET6 Program.cs -(to get the application configuration properties)

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Configuration.AddJsonFile($"appsettings.Dev.json", optional: true);
builder.Configuration.AddEnvironmentVariables();

// projectwide instances
  public IConfiguration _configuration;
        public AccountsAPIController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

// _configuration.GetConnectionString("DefaultConnection");
like image 5
Baron Lugtu Avatar answered Oct 07 '22 17:10

Baron Lugtu