使用 .NET Core 和命令行创建 Windows 服务安装程序

Create a Windows Service installer using .NET Core and command line

我使用此示例创建了一个 ASP.NET 核心 Windows 服务应用程序: https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/host-and-deploy/windows-service/samples/2.x/AspNetCoreService

现在,我想使用命令行安装我的服务,例如“MyService.exe -install”。我知道如果我使用“sc create”会起作用,但我想使用我自己的应用程序来安装和配置我想要的服务。

我找到了一个使用 Toshelf 包的示例,但我使用的是 WebHostBuilder 并且我尝试使用自定义服务配置。服务已安装,但启动时无法使用。

我正在使用 .NET Core 2.2。

我的配置:

HostFactory.Run(x =>
            {
                x.Service<CustomWebHostService>(sc =>
                {
                    sc.ConstructUsing(() => new CustomWebHostService(host));

                    // the start and stop methods for the service
                    sc.WhenStarted(ServiceBase.Run);
                    sc.WhenStopped(s => s.Stop());
                });

                x.RunAsLocalSystem();
                x.StartAutomatically();

                x.SetServiceName("Teste Core");
                x.SetDisplayName("Teste ASP.NET Core Service");
                x.SetDescription("Teste ASP.NET Core as Windows Service.");
            });

我的完整源代码: https://github.com/rkiguti/dotnetcore.windows-service

我像另一个示例一样更改了我的代码,我的服务现在作为控制台应用程序和 windows 服务运行。并且可以使用命令行“MyService.exe install”安装。

我的 program.cs 文件:

class Program
{
    public static void Main(string[] args)
    {
        HostFactory.Run(x =>
        {
            x.Service<ApplicationHost>(sc =>
            {
                sc.ConstructUsing(() => new ApplicationHost());

                // the start and stop methods for the service
                sc.WhenStarted((svc, control) =>
                {
                    svc.Start(control is ConsoleRunHost, args);
                    return true;
                });
                sc.WhenStopped(s => s.Stop());
                sc.WhenShutdown(s => s.Stop());
            });

            x.UseNLog();
            x.RunAsLocalSystem();
            x.StartAutomatically();

            x.SetServiceName("Test Core");
            x.SetDisplayName("Test ASP.NET Core Service");
            x.SetDescription("Test ASP.NET Core as Windows Service.");
        });
    }
}

我的 ApplicationHost.cs 文件:

public class ApplicationHost
{
    private IWebHost _webHost;

    public void Start(bool launchedFromConsole, string[] args)
    {
        if (!launchedFromConsole)
        {
            var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);
            Directory.SetCurrentDirectory(pathToContentRoot);
        }

        IWebHostBuilder webHostBuilder = CreateWebHostBuilder(args);
        _webHost = webHostBuilder.Build();

        _webHost.Start();

        // print information to console
        if (launchedFromConsole)
        {
            var serverAddresses = _webHost.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses;
            foreach (var address in serverAddresses ?? Array.Empty<string>())
            {
                Console.WriteLine($"Listening on: {address}");
                Console.WriteLine("Press Ctrl+C to end the application.");
            }
        }
    }

    public void Stop()
    {
        _webHost?.Dispose();
    }

    private IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddEventLog();
            })
            .ConfigureAppConfiguration((context, config) =>
            {
                // Configure the app here.
            })
            .UseUrls("http://+:8000")
            .UseStartup<Startup>();
}

完整源代码:https://github.com/rkiguti/dotnetcore.windows-service