Skip to content

Instantly share code, notes, and snippets.

@DamianEdwards
Created March 15, 2021 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DamianEdwards/2a493536fed539bc0c1c15713cb0a3bd to your computer and use it in GitHub Desktop.
Save DamianEdwards/2a493536fed539bc0c1c15713cb0a3bd to your computer and use it in GitHub Desktop.
ASP.NET Core IHostingStartup that as soon as the site has started makes a request to itself then shuts itself down
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
[assembly: HostingStartup(typeof(SelfShutdown.ShutdownHostingStartup))]
namespace SelfShutdown
{
public class ShutdownHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
services.AddTransient<IStartupFilter, ShutdownStartupFilter>();
});
}
}
public class ShutdownStartupFilter : IStartupFilter
{
private readonly IHostApplicationLifetime _appLifetime;
private readonly IServerAddressesFeature _serverAddresses;
private readonly ILogger<ShutdownStartupFilter> _logger;
public ShutdownStartupFilter(IHostApplicationLifetime appLifetime, IServer server, ILogger<ShutdownStartupFilter> logger)
{
_appLifetime = appLifetime;
_serverAddresses = server.Features.Get<IServerAddressesFeature>();
_logger = logger;
}
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return builder =>
{
_appLifetime.ApplicationStarted.Register(OnApplicationStarted);
next(builder);
};
}
private void OnApplicationStarted()
{
// Make a request to the site root to force full initialization
var url = _serverAddresses.Addresses.FirstOrDefault(s => s.StartsWith("https://"))
?? _serverAddresses.Addresses.FirstOrDefault(s => s.StartsWith("http://"));
_logger.LogInformation("App startup completed, initiating request to {url}", url);
using var http = new HttpClient();
http.GetStringAsync(url).Wait();
_logger.LogInformation("Request complete, requesting app shutdown");
_appLifetime.StopApplication();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment