ASP.NET Minimal API - Access IConfiguration

Viewed 2083

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();
2 Answers

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>();

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>()

Related