From 19d487683468db5b7e34d449ac105b088cef9b5a Mon Sep 17 00:00:00 2001 From: Michael Becker Date: Sun, 5 Jan 2025 23:39:00 -0500 Subject: [PATCH] play nice to allow for embedding into other host processes e.g. tests --- src/lib/MBS.Web/WebApplication.cs | 33 +++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/lib/MBS.Web/WebApplication.cs b/src/lib/MBS.Web/WebApplication.cs index 76f1c9a..269550c 100644 --- a/src/lib/MBS.Web/WebApplication.cs +++ b/src/lib/MBS.Web/WebApplication.cs @@ -8,6 +8,8 @@ namespace MBS.Web; public abstract class WebApplication : Application { protected abstract int DefaultPort { get; } + public int Port { get { return WebServer.EndPoint.Port; } } + public WebServer WebServer { get; private set; } public string VirtualBasePath { get; set; } = "/"; @@ -40,20 +42,39 @@ public abstract class WebApplication : Application return new WebServer(new IPEndPoint(IPAddress.Any, DefaultPort)); } + private bool shuttingDown = false; + protected override void StopInternal(int exitCode = 0) + { + shuttingDown = true; + if (!SupportEmbeddedHosting) + { + // we do not want to System.Environment.Exit() here + // if we are hosted in another process (e.g. for tests) + base.StopInternal(exitCode); + } + } + + public bool SupportEmbeddedHosting { get; set; } = false; + protected override void OnStartup(EventArgs e) { base.OnStartup(e); - WebServer server = CreateWebServer(); + WebServer = CreateWebServer(); Console.WriteLine("attempting to start server listening on port {0}", DefaultPort); - OnServerCreated(new WebServerCreatedEventArgs(server)); - server.ProcessRequest += server_OnProcessRequest; - server.Start(); + OnServerCreated(new WebServerCreatedEventArgs(WebServer)); + WebServer.ProcessRequest += server_OnProcessRequest; + WebServer.Start(); - while (true) + if (!SupportEmbeddedHosting) { - Thread.Sleep(50); + while (!shuttingDown) + { + Thread.Sleep(50); + } + + WebServer.Stop(); } }