Home > Software design >  .NET 6 Environment based Program.cs
.NET 6 Environment based Program.cs

Time:08-08

Is it possible to have in .NET 6 multiple Program.cs based on environments. Something like we had with Startup.cs where we could use StartupDevelopment, StartupStaging, etc., to place configuration in classes specific for environment? Or the way is to go back to Program.cs with Startup classes?

CodePudding user response:

I think there will be only one program.cs class but you can make different cs files where you can put your configuartions environment based like

developmentConfigurations.cs

Configurations.cs

and configure them in program cs

CodePudding user response:

No, having multiple top-level statements files (i.e. Program.cs) is not possible, cause compiler permits only one such file per project. So you need either switch back to the generic hosting model (the one with Startup classes) or just write environment specific code yourself using builder.Environment/app.Environment checks:

if (builder.Environment.IsDevelopment())
{
    ...
}
else if(builder.Environment.IsEnvironment("SomeCustomEnv"))
{
    ...
}
...

You can extract and move this code to partial Program class(note - no namespace):

public static partial class Program
{
    public static WebApplicationBuilder RegisterDevelopment(this WebApplicationBuilder builder)
    {
        if (builder.Environment.IsDevelopment())
        {
            // ...
        }
        return builder;
    }
    // ... other registration methods, including ones accepting `WebApplication`
}

And call in them in the "main" one:

builder.RegisterDevelopment(); 
// ....
  • Related