Reputation: 20987
I'm trying to figure out an efficient way to configure my Startup.cs
for different builds with out using a lot of nasty IfDefs. If I were to configure a normal class, I would usually just swap out a component in the Dependency Injector and everything would be done, but since the startup class is used to configured DI, this isn't possible.
Currently I'm hard coding things like:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
}).AddIdentityServerAuthentication(AuthenticationRule.ConfigureForStaging());
//.AddIdentityServerAuthentication(AuthenticationRule.ConfigureForProduction());
I have a bunch of statement commented out throughput the code base
const string connection = @"Server=StagingServer.com;Database=MyStagingDB;Trusted_Connection=True;";
//const string connection = @"Server=localhost;Database=MyLocalDB;Trusted_Connection=True;";
This is not very efficient, and definetly error prone. How can I configured my startup class to make switching builds easy?
Upvotes: 1
Views: 97
Reputation: 18125
Here's one idea.
public class Program
{
public static bool IsProduction = false; // shouldn't actually be hard coded.
public static void Main(string[] args)
{
var hostCommon =
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration();
var host =
IsProduction
? hostCommon.UseStartup<StartupProduction>()
: hostCommon.UseStartup<StartupStaging>();
host.Build().Run();
}
}
You could then put the common portions in a Helper class of some kind, and call whatever portions you need for each Startup
class from each individual Startup
class.
If you have more than two environments, you could use a Dictionary<string, Type>
or Dictionary<string, Func<IWebHostBuilder, IWebHostBuilder>>
and key off of the environment name.
Alternatively, you could use the Convention-based approach mentioned by Camilo Terevinto. From Microsoft:
An alternative to injecting IHostingEnvironment is to use a conventions-based approach. The app can define separate Startup classes for different environments (for example, StartupDevelopment), and the appropriate startup class is selected at runtime. The class whose name suffix matches the current environment is prioritized. If the app is run in the Development environment and includes both a Startup class and a StartupDevelopment class, the StartupDevelopment class is used.
Upvotes: 3