// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.ServiceProcess;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Hosting.WindowsServices
{
///
/// Provides an implementation of a Windows service that hosts ASP.NET Core.
///
public class WebHostService : ServiceBase
{
private IWebHost _host;
private bool _stopRequestedByWindows;
///
/// Creates an instance of WebHostService which hosts the specified web application.
///
/// The configured web host containing the web application to host in the Windows service.
public WebHostService(IWebHost host)
{
_host = host;
}
protected sealed override void OnStart(string[] args)
{
OnStarting(args);
_host
.Services
.GetRequiredService()
.ApplicationStopped
.Register(() =>
{
if (!_stopRequestedByWindows)
{
Stop();
}
});
_host.Start();
OnStarted();
}
protected sealed override void OnStop()
{
_stopRequestedByWindows = true;
OnStopping();
_host?.Dispose();
OnStopped();
}
///
/// Executes before ASP.NET Core starts.
///
/// The command line arguments passed to the service.
protected virtual void OnStarting(string[] args) { }
///
/// Executes after ASP.NET Core starts.
///
protected virtual void OnStarted() { }
///
/// Executes before ASP.NET Core shuts down.
///
protected virtual void OnStopping() { }
///
/// Executes after ASP.NET Core shuts down.
///
protected virtual void OnStopped() { }
}
}