碰到这个问题,改造完成后写下来备忘,注意这里的.NET应用指的不是.NET Framework,.NET Framework的玩法参见:
给WPF程序添加以Windows服务的方式运行的功能 - 简书 (jianshu.com)
整个过程就两步:
- 添加第一个类Worker.cs
namespace MyDotNETService
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}
添加第二个类program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Logging.EventLog;
using WindowsSecurityLogCollectorService;
//Added by Darwin
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(options =>
{
options.ServiceName = "My DotNET Service";
});
LoggerProviderOptions.RegisterProviderOptions<
EventLogSettings, EventLogLoggerProvider>(builder.Services);
builder.Services.AddSingleton<Worker>();
builder.Services.AddHostedService<Worker>();
IHost host= builder.Build();
//above added by darwin
//IHost host = Host.CreateDefaultBuilder(args)
// .ConfigureServices(services =>
// {
// services.AddHostedService<Worker>();
// })
// .Build();
host.Run();
- 修改类里的内容使适合自己的应用
2.1 Worker类中的命名空间记得改,还有ExecuteAsync里的工作改成自己的内容,基本上只需要改_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
这一行即可。
2.2 Program.cs中的服务名称My DotNET Service
记得改成自己的。
- 补充一下服务的安装与卸载
(以下命令在管理员权限运行的PowerShell中进行)
3.1 服务的安装
New-Service -Name "Service Name" -BinaryPathName "ServiceExeFullPath"
3.2 服务的卸载
Remove-Service -Name "Service Name"
这个卸载的方法需要PowerShell 6.0或者以上版本,安装命令:
winget install --id microsoft.powershell --source winget
网友评论