Net Core Based TopShelf running in service mode

Net Core Based TopShelf running in service mode

1 Background

Net Core is the essence of a window procedure (expressions in windows is console window). Customer and product manager of the company's feedback If you have accidentally closed the window, the entire program is shut down, the consequences could be very serious, so the software will be made by TopShelf service model, installed by cmd command, start, stop, uninstall program.

2 Advantages

2.1 Service mode can be set to restart condition

Such as memory more than 1G, setting a reboot.

2.2 avoid misuse

Avoid window mode mistakenly shut down.

3. Use

3.1 GUI package installed Topshelf

4 Configuration

Program.cs file, see comments

            var rc = HostFactory.Run(x =>                        
            {
                /*运行MainService主程序*/
                //创建一个MainService服务实例
                x.Service<MainService>(s =>                      
                {
                    //通知TopShelf 这里有一个MainService类型的服务,通过s来配置他的参数
                    s.ConstructUsing(name => new MainService(Directory.GetCurrentDirectory())); 
                    //TopShelf启动服务         
                    s.WhenStarted(tc => tc.Start());  
                    //TopShelf停止服务           
                    s.WhenStopped(tc => tc.Stop());              
                });
                //x.RunAs("username", "password");也可以用户名密码方式运行
                x.RunAsLocalSystem();
                //服务描述
                x.SetDescription("WEBAPIService");     
               //服务显示名称  
                x.SetDisplayName("WEBAPIService");      
                //服务名称          
                x.SetServiceName("WEBAPIService");               
            });             
            //转化退出编码                                     
            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());  
            //设置退出编码
            Environment.ExitCode = exitCode;

5 The main program runs

MainService.cs file, see the comments.

namespace IBMS.WEBAPI
{
    public class MainService
    {    //创建一个webhost实例
          private IWebHost _webHost;
          private readonly string _contentRoot;
        
          public MainService(string contentRoot)
          {
              _contentRoot = contentRoot;
          }
         //服务模式启动程序
          public void Start()
          {
            // 获取链接字符串
            var config = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile("appsettings.json")
                  .Build();
           //配置webhost
            _webHost = new WebHostBuilder()
                  .UseKestrel()
                  .UseContentRoot(_contentRoot)
                  .UseUrls(config["urls"])
                  .UseStartup<Startup>()
                  .UseSerilog()
                  .Build();
            var _logger = _webHost.Services.GetService<ILoggerFactory>().CreateLogger<MainService>();
            _logger.Log(LogLevel.Information, new EventId(1001, "Starting"), "Service Starting");
            //种子数据种入数据库
            using (var scope = _webHost.Services.CreateScope())
            {
                try
                {
                    var context = scope.ServiceProvider.GetService<IIBMSContext>();

                    var concreteContext = (IBMSContext)context;
                    concreteContext.Database.Migrate();
                    SeedData.Initialize(concreteContext);
                }
                catch (Exception ex)
                {
                //    var _logger = scope.ServiceProvider.GetRequiredService<ILogger<MainService>>();
                    _logger.LogError(ex, "An error occurred while migrating or initializing the database.");
                }
            }
            //启动webhost
            _webHost.Start();
          }
        
          public void Stop()
          {
              _webHost?.Dispose();
          }
    }
}

6 Start the installation instructions

IBMS.WEBAPI.exe install
IBMS.WEBAPI.exe start

7 Stop uninstall instructions

IBMS.WEBAPI.exe uninstall
IBMS.WEBAPI.exe stop

8 services running schematic

Consideration about 9

If you know or have heard there are problems solutions or open source projects, please inform, let me also common under progress in this thanked.

9.1 How to make installation (Services 3-4)

For example, on the windows msi installer tools.

9.2 There are no windows on the configuration tool

For example, the configuration tool can read the parameter configuration file (config.js, my.ini, appsettings.json, nginx.conf , redis.windows.conf ...), and can be configured via the GUI management tools of human the user interaction data arranged as own configuration corresponding to the configuration file.
E.g:

9.3 whether this is similar to the watchdog monitoring service, set to start service stop (installation uninstall) tools

E.g:


If you know the solution to the problem more than 3:00 or open source project, I urge us, thank you.

Guess you like

Origin www.cnblogs.com/JerryMouseLi/p/11537372.html