ASP.NET Minimal API - Access IConfiguration
Asked Answered
W

3

22

Is it possible to access the the IConfiguration in the new ASP.NET Minimal API? I do not see the possibility to do such thing.

using Microsoft.AspNetCore.Components;
using MudBlazor.Services;

var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddMyServiceWithConfiguration(XXXX.Configuration);

var app = builder.Build();

....

app.Run();
Waikiki answered 7/9, 2021 at 15:16 Comment(0)
W
34

You can use builder.Configuration. In this example, the connection string is retrieved in the second line of actual code:

using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("TodoDb") 
                       ?? "Data Source=todos.db";


builder.Services.AddSqlite<TodoDb>(connectionString)
                .AddDatabaseDeveloperPageExceptionFilter();

The WebApplicationBuilder.Configuration property is a Microsoft.Extensions.ConfigurationManager instance that implements IConfigurationRoot and IConfiguration, so it can be used to load config settings or use extension methods like GetConnectionString

Once the application is built, configuration is accessible through the WebApplication.Configuration property. This is just a call to Services.GetRequiredService<IConfiguration>():

public IConfiguration Configuration => 
    _host.Services.GetRequiredService<IConfiguration>();
Wildebeest answered 7/9, 2021 at 15:24 Comment(0)
M
2

You can access ConfigurationManager (builder.Configuration) which is an implementation of IConfigurationBuilder, IConfigurationRoot and IConfiguration

After your application is build (builder.Build()), you can access it using app.Services.GetRequiredService<IConfiguration>()

Maomaoism answered 20/5, 2022 at 9:33 Comment(0)
I
0

I tried acepted answer but did not work in my application (.NET 8.0), so I accessed the configuration as shown here.

var app = WebApplication.Create(args);

var message = app.Configuration["HelloKey"] ?? "Config failed!";
Indiscrete answered 11/4 at 1:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.