zl程序教程

您现在的位置是:首页 >  系统

当前栏目

windows 服务开发组件之Topshelf

2023-09-11 14:21:52 时间

常用的windows服务开发有vs自带的windows服务开发,但是操作起来不是很便利,相比Topshelf后者更加的方便,且易于调试,安装,卸载.

1、安装

通过nuget搜索最新版本的topshelf,并安装到控制台项目(netcore和net均可)中,一般都是用控制台调试,然后通过topshelf安装成windows服务.

官方文档地址 组件支持的功能基本满足日常开发需求,如常规的服务描述,服务异常处理,服务恢复,服务启动模式等等不一一赘述,自行查阅文档.

 

2、代码

        public static void Run<TExecutedService>(Action<TopshelfOptions> configurator) where TExecutedService : TopshelfService
        {
            var options=new TopshelfOptions();
            configurator?.Invoke(options);
            if (string.IsNullOrEmpty(options.ServiceName))
                throw new ArgumentNullException(nameof(options.ServiceName));
            if (string.IsNullOrEmpty(options.DisplayName))
                throw new ArgumentNullException(nameof(options.DisplayName));

            HostFactory.Run(configurater =>
            {
                configurater.Service<TExecutedService>(service =>
                {
                    service.ConstructUsing(hostSetting =>
                    {
                        return ApplicationConfiguration.Current.Provider.GetRequiredService<TExecutedService>();
                    });
                    service.WhenStarted(s => s.Start());
                    service.WhenStopped(s => s.Stop());
                });
                configurater.RunAsLocalSystem();
                configurater.SetDescription(options.Description?? options.DisplayName);
                configurater.SetDisplayName(options.DisplayName);
                configurater.SetServiceName(options.ServiceName);
                configurater.OnException(exception =>
                {
                    Console.WriteLine("业务执行异常,异常信息如下:" + exception.Message + "堆栈信息如下:" + exception.StackTrace);
                });
            });
        }