Last active
April 16, 2021 20:29
-
-
Save manoj-choudhari-git/96f5efeb33582bf0d834ae2d6a367568 to your computer and use it in GitHub Desktop.
Single Startup files with environment specific conditional code paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Program.cs | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
CreateHostBuilder(args).Build().Run(); | |
} | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureWebHostDefaults(webBuilder => | |
{ | |
// Notice the UseStartup overload specifying the class name | |
webBuilder.UseStartup<Startup>(); | |
}); | |
} | |
// Startup.cs | |
public class Startup | |
{ | |
private readonly IWebHostEnvironment env; | |
public Startup(IConfiguration configuration, IWebHostEnvironment env) | |
{ | |
Configuration = configuration; | |
this.env = env; | |
} | |
public IConfiguration Configuration { get; } | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
if(this.env.IsEnvironment("Security")) | |
{ | |
// Setup services for security environment | |
} | |
else if(this.env.IsDevelopment()) | |
{ | |
// Setup stubs for external services | |
} | |
else | |
{ | |
// Setup services required for other environments | |
} | |
// common services | |
services.AddControllersWithViews(); | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
} | |
else | |
{ | |
app.UseExceptionHandler("/Home/Error"); | |
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. | |
app.UseHsts(); | |
} | |
app.UseHttpsRedirection(); | |
app.UseStaticFiles(); | |
app.UseRouting(); | |
app.UseAuthorization(); | |
app.UseEndpoints(endpoints => | |
{ | |
endpoints.MapControllerRoute( | |
name: "default", | |
pattern: "{controller=Home}/{action=Index}/{id?}"); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment