NetCore 2.1 Generic Host as a service

前端 未结 3 1081
北恋
北恋 2021-02-08 18:07

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.

I\

3条回答
  •  梦如初夏
    2021-02-08 19:00

    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()
                .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);
        }
    }
    

提交回复
热议问题