使用Topshelf部署.net core windows服务 Demo
引用相关 包
<ItemGroup> <PackageReference Include="Topshelf" Version="4.2.1" /> </ItemGroup>
设置项目类型
<Project Sdk="Microsoft.NET.Sdk.Worker">
修改 Program.cs
using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;public class Program{ public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureServices(services => { services.AddHostedService<VideosWatcher>(); });}
修改后
public class Program { public static void Main(string[] args) { HostFactory.Run(x => { x.SetServiceName("TopshelfDemo.ServiceName"); x.SetDisplayName("TopshelfDemo.DisplayName"); x.SetDescription("TopshelfDemo.Description"); x.Service<IHost>(s => { s.ConstructUsing(() => CreateHostBuilder(args).Build()); s.WhenStarted(service => { service.Start(); }); s.WhenStopped(async service => { await service.StopAsync(); }); }); x.StartAutomatically(); }); } const string OutputInfoTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}{NewLine}"; const string OutputPropTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Properties:l}{NewLine}{Exception}{NewLine}"; public static IHostBuilder CreateHostBuilder(string[] args) => Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)#if DEBUG .UseEnvironment(Environments.Development)#else .UseEnvironment(Environments.Staging) //.UseEnvironment(Environments.Production)
No comments:
Post a Comment