Skip to content

Instantly share code, notes, and snippets.

@nickalbrecht
Last active April 26, 2024 03:30
Show Gist options
  • Save nickalbrecht/83e0c96b1b24d0d2de0532835667074b to your computer and use it in GitHub Desktop.
Save nickalbrecht/83e0c96b1b24d0d2de0532835667074b to your computer and use it in GitHub Desktop.
Minimum code needed to run/experiment with functionality from an AspNetCore project
/*
References (F4 - Additional References - Add...)
~~~~~~~~~~~~~~~~~~~
<Your AspNetCore site assembly>
* Check Reference ASP.NET Core
Using (F4 - Additional Namespace Imports)
~~~~~~~~~~~~~~~~~~~
Microsoft.AspNetCore.Hosting
Microsoft.Extensions.Configuration
Microsoft.Extensions.DependencyInjection
System.Threading.Tasks
*/
#region Boilderplate for AspNetCore playground in LinqPad
public IServiceScope serviceScope;
void SetupPlayground()
{
//HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();//Setup NHibernate Profiling
var sw = Stopwatch.StartNew(); //Just for tracking how long Setup() takes
$"Setting up playground: 0 seconds".Dump();
//an IWebHostEnvironment for Linqpad
var hostingEnvironment = new LinqPadHostingEnvironment(@"C:\Users\Nick\source\repos\WebApplication9");
//Initialize and setup ConfigurationManager
var config = new Microsoft.Extensions.Configuration.ConfigurationManager();
config.SetBasePath(hostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile(string.Format("appsettings.{0}.json", (object)hostingEnvironment.EnvironmentName), true, true);
config.AddUserSecrets("dfe1bb4f-1634-453b-b602-a68d00741aba")
.AddInMemoryCollection([new KeyValuePair<string, string>("Environment", "Development")])
.Build();
//Dependency Injection
var services = new ServiceCollection();
services.AddSingleton<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>(hostingEnvironment);
services.AddSingleton<Microsoft.AspNetCore.Hosting.IHostingEnvironment>(hostingEnvironment); //Only if you need it
//public static void SetupConfiguration(ConfigurationManager configuration)
Program.SetupConfiguration(config);
$"Project Configuration ready: {sw.Elapsed.TotalSeconds} seconds".Dump();
//public static void ConfigureServices(IServiceCollection services, ConfigurationManager configuration, IHostEnvironment environment)
Program.ConfigureServices(services, config, hostingEnvironment);
$"Project Services ready: {sw.Elapsed.TotalSeconds} seconds".Dump();
var serviceProvider = services.BuildServiceProvider();
serviceScope = serviceProvider.CreateScope();
$"Provider & scope created: {sw.Elapsed.TotalSeconds} seconds".Dump();
sw.Stop();
$"Playground setup completed Startup Completed: {sw.Elapsed.TotalSeconds} seconds".Dump();
}
public class LinqPadHostingEnvironment : IWebHostEnvironment, Microsoft.Extensions.Hosting.IHostingEnvironment, Microsoft.AspNetCore.Hosting.IHostingEnvironment
{
public LinqPadHostingEnvironment(string aspNetCoreProjectDirectory)
{
EnvironmentName = "Development";
ApplicationName = "LinqPad";
ContentRootPath = aspNetCoreProjectDirectory;
WebRootPath = System.IO.Path.Combine(aspNetCoreProjectDirectory, "wwwroot");
}
public string EnvironmentName { get; set; }
public string ApplicationName { get; set; }
public string WebRootPath { get; set; }
public Microsoft.Extensions.FileProviders.IFileProvider WebRootFileProvider { get; set; }
public string ContentRootPath { get; set; }
public Microsoft.Extensions.FileProviders.IFileProvider ContentRootFileProvider { get; set; }
}
#endregion
void Main()
{
try
{
/* Useful for forcing a new process every time */
//Util.NewProcess = true;
//Sets up playground for use
SetupPlayground();
//Optionally begin transaction here
//DO STUFF HERE
//optionally commit transaction
}
catch (Exception ex)
{
ex.Dump();
//optionally rollback transaction
}
finally
{
serviceScope?.Dispose();
}
}
//While your default implimentation will likely have this as a minimal Program class, we need to split it up and ilsolate the setup of Confiration and Services so that they can be used from LinqPad
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
//1. Initialize Configuration
SetupConfiguration(builder.Configuration);
//2. Configure the services needed
ConfigureServices(builder.Services, builder.Configuration, builder.Environment);
//3. Configure the middleware pipeline
var app = builder.Build();
ConfigureMiddleware(app);
//RUN!
app.Run();
}
public static void SetupConfiguration(ConfigurationManager configuration)
{
//Setup & add additional configuration sources
}
/// <param name="configuration">So that we can add Options to the services based off of confiration sections</param>
/// <param name="environment">So that we can differ our services setup based on IsDevelopment() </param>
public static void ConfigureServices(IServiceCollection services, ConfigurationManager configuration, IHostEnvironment environment)
{
//Add services
services.AddControllersWithViews();
}
private static void ConfigureMiddleware(WebApplication app) //Made private because we don't access this method externally when running in LinqPad
{
if (!app.Environment.IsDevelopment()) {
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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
}
}
@nickalbrecht
Copy link
Author

Updated with what I currently use with .NET Core 8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment