NetCore 2.1 通用主机即服务 [英] NetCore 2.1 Generic Host as a service

查看:31
本文介绍了NetCore 2.1 通用主机即服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用最新的 Dotnet Core 2.1 运行时构建 Windows 服务.我没有托管任何 aspnet,我不想或不需要它来响应 http 请求.

I'm trying to build a Windows Service using the latest Dotnet Core 2.1 runtime. I'm NOT hosting any aspnet, I do not want or need it to respond to http requests.

我遵循了示例中的代码:https://github.com/aspnet/Docs/tree/master/aspnetcore/fundamentals/host/generic-host/samples/2.x/GenericHostSample

I've followed the code found here in the samples: https://github.com/aspnet/Docs/tree/master/aspnetcore/fundamentals/host/generic-host/samples/2.x/GenericHostSample

我还阅读了这篇文章:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.1

当使用 dotnet run 在控制台窗口内运行时,代码运行良好.我需要它作为 Windows 服务运行.我知道有 Microsoft.AspNetCore.Hosting.WindowsServices,但那是用于 WebHost,而不是通用主机.我们会使用 host.RunAsService() 作为服务运行,但我在任何地方都看不到它.

The code works great when run inside of a console window using dotnet run. I need it to run as a windows service. I know there's the Microsoft.AspNetCore.Hosting.WindowsServices, but that's for the WebHost, not the generic host. We'd use host.RunAsService() to run as a service, but I don't see that existing anywhere.

如何将其配置为作为服务运行?

How do I configure this to run as a service?

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace MyNamespace
{
    public class Program
    {


        public static async Task Main(string[] args)
        {
            try
            {
                var host = new HostBuilder()
                    .ConfigureHostConfiguration(configHost =>
                    {
                        configHost.SetBasePath(Directory.GetCurrentDirectory());
                        configHost.AddJsonFile("hostsettings.json", optional: true);
                        configHost.AddEnvironmentVariables(prefix: "ASPNETCORE_");
                        configHost.AddCommandLine(args);
                    })
                    .ConfigureAppConfiguration((hostContext, configApp) =>
                    {
                        configApp.AddJsonFile("appsettings.json", optional: true);
                        configApp.AddJsonFile(
                            $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json",
                            optional: true);
                        configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
                        configApp.AddCommandLine(args);
                    })
                    .ConfigureServices((hostContext, services) =>
                    {
                        services.AddLogging();
                        services.AddHostedService<TimedHostedService>();
                    })
                    .ConfigureLogging((hostContext, configLogging) =>
                    {
                        configLogging.AddConsole();
                        configLogging.AddDebug();

                    })

                    .Build();

                await host.RunAsync();
            }
            catch (Exception ex)
            {



            }
        }


    }

    #region snippet1
    internal class TimedHostedService : IHostedService, IDisposable
    {
        private readonly ILogger _logger;
        private Timer _timer;

        public TimedHostedService(ILogger<TimedHostedService> logger)
        {
            _logger = logger;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is starting.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(5));

            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            _logger.LogInformation("Timed Background Service is working.");
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
    #endregion
}

我再说一遍,这不是托管 ASP.NET Core 应用程序.这是一个通用的主机构建器,而不是 WebHostBuilder.

I repeat, this is not to host an ASP.NET Core app. This is a generic hostbuilder, not a WebHostBuilder.

推荐答案

正如其他人所说,您只需要重用 IWebHost 接口的代码,这里是一个示例.

As others have said you simply need to reuse the code that is there for the IWebHost interface here is an example.

public class GenericServiceHost : ServiceBase
{
    private IHost _host;
    private bool _stopRequestedByWindows;

    public GenericServiceHost(IHost host)
    {
        _host = host ?? throw new ArgumentNullException(nameof(host));
    }

    protected sealed override void OnStart(string[] args)
    {
        OnStarting(args);

        _host
            .Services
            .GetRequiredService<IApplicationLifetime>()
            .ApplicationStopped
            .Register(() =>
            {
                if (!_stopRequestedByWindows)
                {
                    Stop();
                }
            });

        _host.Start();

        OnStarted();
    }

    protected sealed override void OnStop()
    {
        _stopRequestedByWindows = true;
        OnStopping();
        try
        {
            _host.StopAsync().GetAwaiter().GetResult();
        }
        finally
        {
            _host.Dispose();
            OnStopped();
        }
    }

    protected virtual void OnStarting(string[] args) { }

    protected virtual void OnStarted() { }

    protected virtual void OnStopping() { }

    protected virtual void OnStopped() { }
}

public static class GenericHostWindowsServiceExtensions
{
    public static void RunAsService(this IHost host)
    {
        var hostService = new GenericServiceHost(host);
        ServiceBase.Run(hostService);
    }
}

这篇关于NetCore 2.1 通用主机即服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆