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 ?
Here is my default Program.cs
that ASP.NET Core 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";
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...