I have a connection string setup I used in Dotnet5 and prior versions of Dotnet Core and it's worked great, but upgrading to Dotnet6 and I have no idea how to get the following to work (basically a connection string i use called DBConn is the part that needs to change - reads the connection string from appsettings.json as typical):
In the Program.cs file:
public class Program
{
public static string DBConn { get; set; }
public static void Main(string[] args)
{
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json", true, true).Build();
DBConn = config.GetConnectionString("DBConn");
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
In Dotnet6, there is no Program class or Main method (or somehow it's incorporated), so I can't use the database connection code as written. While the docs claim that the Program.cs file IS the Main method - I don't see how this even works nor how to do what's worked for years to work here. I presume there is a better way to get connection string from the appsettings.json file, but I have no idea how to do it (the docs are limited to Dotnet5)
Here's what the program.cs looks like in DotNet6:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();