Windows Service-Action in .NET Core
Run Nuget Packet Manager and implement following packages:
Microsoft.Extensions.Logging and Microsoft.Extensions.Hosting.WindowsServices
To make a windows-service in .NET Core, start by selecting a Worker service project
like seen below.
In Program.cs modify the code so it looks like this:
To make a windows-service in .NET Core, start by selecting a Worker service project
like seen below.
In Program.cs modify the code so it looks like this:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
.ConfigureLogging( options => options.AddFilter
(level => level >= LogLevel.Information))
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService
()
.Configure(config =>
{
config.LogName = "My Own WorkerService";
config.SourceName = "My Own WorkerService Source";
});
}).UseWindowsService();
}
Here in this example the windows service is named My Own WorkerService But you can name whatever name you wish.
In the Worker.cs (computer-generated) you can change the code as in this example.
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace MyOwnWorkerService
{
public class Worker : BackgroundService
{
private readonly ILogger _logger;
public Worker(ILoggerlogger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
//Here is the actual meat of the windows-service (Just an example)
_logger.LogInformation("My Own Worker-Service running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}
Pressing ctrl-F5 to run the code, the following is displayed:
To register it as Windows-service run this command in a DOS-window.:
sc create "My Own WorkerService" binpath=c:\mywinservice\MyOwnWorkerService.exe
Now you can start or stop the Windows-service and watch the logging in the Event-log.
To register it as Windows-service run this command in a DOS-window.:
sc create "My Own WorkerService" binpath=c:\mywinservice\MyOwnWorkerService.exe
Now you can start or stop the Windows-service and watch the logging in the Event-log.