Search code examples
c#asp.net-core.net-core.net-6.0

How to use appsettings.json in Asp.net core 6 Program.cs file


I'm trying to access appsettings.json in my Asp.net core v6 application Program.cs file, but in this version of .Net the Startup class and Program class are merged together and the using and another statements are simplified and removed from Program.cs. In this situation, How to access IConfiguration or how to use dependency injection for example ?

Code

Here is my default Program.cs that Asp.net 6 created for me

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

For example , I want to use appsettings.json instead of hard typed connectionstring in this line :

options.Configuration = "localhost:6379";

Solution

  • In case that we have in appsettings

    "settings": {
        "url": "myurl",
        "username": "guest",
        "password": "guest"
      }
    

    and we have the class

    public class Settings
        {
            public string Url { get; set; }
            public string Username { get; set; }
            public string Password { get; set; }
        }
    

    we can use also

    var settings = builder.Configuration.GetSection("Settings").Get<Settings>();
    
    var url = settings.Url;
    

    etc....