Previously, creating an ASP.NET Core project template would create two C# files, Program.cs and Startup.cs. In the Startup class you would receive an IConfiguration through the constructor, which you could then use to retrieve configuration values. It looked something like this:
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
string connectionString = Configuration.GetConnectionString("Foo");
}
}
But now from .NET 6, there's a new template, where there's only a single Program.cs file, in which you both add services to the DI container, and configure the HTTP request pipeline. It looks something like this (it also takes advantage of the new C# 9.0 top-level statements feature):
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseRouting();
app.Run();
Now, in this new style, how can I access an IConfiguration here in Program.cs?
If I do:
var configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();
I get the following warning:
ASP0000: Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.
But there's no Configure method here as I don't have a Startup class.
What are you supposed to do in this situation? How would you get an IConfiguration here in this new template without having to create a separate Startup class?