August 5, 2021

TopSelf 示例

    class Program
    {
        static void Main(string[] args)
        {
            var rc = HostFactory.Run(x =>
            {
                x.Service<WSService>(s =>
                {
                    s.ConstructUsing(tc => new WSService(args));
                    s.WhenStarted((s, h) => s.Start(h));
                    s.WhenStopped((s, h) => s.Stop(h));
                });

                x.SetDisplayName("FallCSC Websocket");
                x.SetDescription("FallCSC Websocket 服务");
                x.SetServiceName("FallCSCWebsocket");

                x.RunAsLocalSystem();

                // 自动启用服务
                x.StartAutomatically();

                x.EnableServiceRecovery(rc =>
                {
                    // 一分钟后重启
                    rc.RestartService(1);
                });
            });

            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
            Environment.ExitCode = exitCode;
        }
    }

    public class WSService : ServiceControl
    {
        private readonly string[] args;
        private IHost host;

        public WSService(string[] args)
        {
            this.args = args;
        }

        public bool Start(HostControl hostControl)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            var builder = CreateHostBuilder(args.Where(arg => arg != "--console").ToArray());

            if (isService)
            {
                var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
                var pathToContentRoot = Path.GetDirectoryName(pathToExe);
                builder.UseContentRoot(pathToContentRoot);
            }

            host = builder.Build();
            host.Start();

            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            host.StopAsync();
            return true;
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
    }