dir.by  
  Search  
Programming, development, testing
Windows Service (using C#)
Loading parameters from appsettings.json for application C# Windows Service (library .NET Core and using Worker)
  Looked at 1753 times    
 Loading parameters from appsettings.json for application C# Windows Service (library .NET Core and using Worker) 
last updated: 17 April 2023
Download the service with the source code:
MyWorkerServiceJsonCore1.zip ...
Size: 4 kb
Step 1. Open Visual Studio
If you do not have Visual Studio installed you need install Visual Studio...
Open Visual Studio 2022
or
Open Visual Studio 2019
Step 2. Open the project C# Windows Service
Step 3. Add the code to the file Program.cs
Let's add lines marked in blue.
This is the initialization of the json file with a new added class ApplicationOptions and a new section ApplicationOptions.
  C#     File Program.cs
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
using MyWorkerServiceCore1.Options;

namespace MyWorkerServiceCore1
{
     public class Program
     {
          public static string EventLogName = "My Worker Service1";
          public static string EventLogSource = "My App1";

          public static void Main(string[] args)
          {
               CreateHostBuilder(args).Build().Run();
          }

          public static IHostBuilder CreateHostBuilder(string[] args) =>
               Host.CreateDefaultBuilder(args)
               .ConfigureLogging(options => options.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Information))
               .ConfigureServices((hostContext, services) =>
               {
                    IConfiguration configuration = hostContext.Configuration;
                    services.Configure<ApplicationOptions>(configuration.GetSection("ApplicationOptions"));

                    services.AddHostedService<Worker>()
                    .Configure<EventLogSettings>(config =>
                    {
                         config.LogName = EventLogName;
                         config.SourceName = EventLogSource;
                    });
               }).UseWindowsService();
     }
}
Step 4. Add the code to the file appsettings.json
Added a new section ApplicationOptions.
Added a new parameter MyName with a value of Evgen.
  File appsettings.json
{
     "ApplicationOptions": {
          "MyName": "Evgen"
     },
     "Logging": {
          "LogLevel": {
               "Default": "Information",
               "Microsoft": "Warning",
               "Microsoft.Hosting.Lifetime": "Information"
          }
     }
}
Step 5. Create a new file ApplicatioOptions.cs
Let's create a new folder Options like this:
  D:/MyWorkerServiceCore1/Options
 
Inside the Options folder, create a new file ApplicatioOptions.cs
In this file, the class ApplicatioOptions with the parameter MyName is the same as the section in the file appsettings.json
  File ApplicationOptions.cs
using System.Text;

namespace MyWorkerServiceCore1.Options
{
     public class ApplicationOptions
     {
          public string MyName { get; set;}
     }
}
Step 6. Add the code to the file Worker.cs
  File Worker.cs
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MyWorkerServiceCore1.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MyWorkerServiceCore1
{
     public class Worker : BackgroundService
     {
          private readonly ILogger<Worker> _logger;
          private readonly ApplicationOptions _applicationOptions;

          public Worker(ILogger<Worker> logger , IOptions<ApplicationOptions> options)
          {
               _logger = logger;
               _applicationOptions = options.Value;
          }

          protected override async Task ExecuteAsync(CancellationToken stoppingToken)
          {
               while (!stoppingToken.IsCancellationRequested)
               {
                    _logger.LogInformation("User: " + _applicationOptions.MyName);

                    _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                    await Task.Delay(1000, stoppingToken);
               }
          }
     }
}
Explanation:
create object applicatioOptions
public class Worker : BackgroundService
{
     private readonly ApplicationOptions _applicationOptions;

     public Worker(ILogger<Worker> logger , IOptions<ApplicationOptions> options)
     {
          _logger = logger;
          _applicationOptions = options.Value;
     }
}

Explanation:
In the constructor Worker
The IOptions<ApplicationOptions> options parameter is automatically created.
Then, inside the constructor, set _applicationOptions = options.Value;.
In the system EventViewer we show the value of the parameter MyName
_logger.LogInformation("User: " + _applicationOptions.MyName);


On the screen we will see Evgen
Step 7. Launching the project
 
Note!
To run the program as WindowsService you need:
register the exe file in the system and run it as Windows Service...
 
← Previous topic
Create a new application C# Windows Service (library .NET Core and use Worker)
 
Next topic →
How to open a Notepad app from C# Windows Service | library .NET Core and use Worker
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
Technology .NET Framework
Create a new application C# Windows Service (.NET Framework)
C# Windows Service (.NET Framework) with the username. Event when user logs in/out of Windows
Create folder "My Application" under folder "Application and Services logs" | Event Viewer
Technology .NET Core
Create a new application C# Windows Service (library .NET Core and use Worker)
Loading parameters from appsettings.json for application C# Windows Service (library .NET Core and using Worker)
How to open a Notepad app from C# Windows Service | library .NET Core and use Worker
Doing publish a project (compiling and assembling a project) "C# Windows Service" | library .NET Core using Worker
How to register your exe file as Windows Service. Start/stop your Windows Service on the system Windows | library .NET Core using Worker

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика