Access environment name in Program.Main in ASP.NET Core

I think the easiest solution is to read the value from the ASPNETCORE_ENVIRONMENT environment variable and compare it with Environments.Development:

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var isDevelopment = environment == Environments.Development;

[New Answer using ASP 6.0 minimal API]:

If you are using ASP 6.0 minimal API it's very simple by using WebApplication.Environment:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

if (!app.Environment.IsProduction())
{
    // ...
}

app.MapGet("/", () => "Hello World!");

app.Run();

======================================

[Old Answer]

This is my solution (written for ASP.NET Core 2.1):

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        var hostingEnvironment = services.GetService<IHostingEnvironment>();
        
        if (!hostingEnvironment.IsProduction())
           SeedData.Initialize();
    }

    host.Run();
}

In .NET core 3.0

using System;
using Microsoft.Extensions.Hosting;

then

var isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == Environments.Development;