Ivan ho ho ho
Ivan ho ho ho

Reputation: 59

.NET 6 Environment based Program.cs

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?

Upvotes: 0

Views: 2015

Answers (2)

Guru Stron
Guru Stron

Reputation: 142973

No, having multiple top-level statements files (i.e. Program.cs) is not possible, because the 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(); 
// ....

Upvotes: 2

n___dv
n___dv

Reputation: 324

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

Upvotes: 1

Related Questions