public void CloneEventHandlers(IRestServer server) { if (BeforeStarting != null) { foreach (var action in BeforeStarting.GetInvocationList().Reverse().Cast <ServerEventHandler>()) { server.BeforeStarting += action; } } if (AfterStarting != null) { foreach (var action in AfterStarting.GetInvocationList().Reverse().Cast <ServerEventHandler>()) { server.AfterStarting += action; } } if (BeforeStopping != null) { foreach (var action in BeforeStopping.GetInvocationList().Reverse().Cast <ServerEventHandler>()) { server.BeforeStopping += action; } } if (AfterStopping != null) { foreach (var action in AfterStopping.GetInvocationList().Reverse().Cast <ServerEventHandler>()) { server.AfterStopping += action; } } }
protected void OnBeforeStarting() { OnBeforeStart?.Invoke(); if (BeforeStarting == null) { return; } var exceptions = InvokeServerEventHandlers(BeforeStarting.GetInvocationList().Reverse().Cast <ServerEventHandler>()); if (exceptions.Count > 0) { throw new AggregateException(exceptions); } }
public override void Start() { if (IsDisposed) { throw new ObjectDisposedException(GetType().FullName); } if (IsListening || IsStarting || IsStopping) { return; } IsStarting = true; var exceptionWasThrown = false; try { // 1. Reset CancellationTokenSource TokenSource?.Dispose(); TokenSource = new CancellationTokenSource(); // 2. Execute BeforeStarting event handlers BeforeStarting?.Invoke(this); // 3. Optionally autoscan for routes if (Router.RoutingTable.Count == 0 && Options.EnableAutoScan) { Router.Register(RouteScanner.Scan()); } // 4. Configure and start the listener Listener.Start(); // 5. Start the request handler thread RequestHandler.Start(); // 6. Execute AfterStarting event handlers AfterStarting?.Invoke(this); } catch (HttpListenerException hl) when(hl.ErrorCode == 32) { /* * When the port you are attempting to bind to is already in use * by another application, the error can sometimes be unintuitive. */ exceptionWasThrown = true; var message = $"One or more ports are already in use by another application."; var exception = new ArgumentException(message, hl); Logger.LogCritical(exception, message); throw exception; } catch (Exception e) { exceptionWasThrown = true; Logger.LogCritical(e, "An unexpected error occured when attempting to start the server"); throw; } finally { if (exceptionWasThrown) { Listener.Stop(); TokenSource.Cancel(); } IsStarting = false; } }