fred_
fred_

Reputation: 1696

how to pass a string to a .NET worker service?

I have a worker service in .NET 5, that will monitor a folder on a PC and a MAC.

I would need the end user to pass the folder to watch to the service worker.

I saw the override void OnCustomCommand(int command) but it's only for an int.

Any idea on how the end user can pass the folder to the service?

Upvotes: 3

Views: 1987

Answers (1)

Frank
Frank

Reputation: 317

You could use one of the next two approaches.

First approach: Pass the file path through appsettings.json file like this example:

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

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) => {
        //Obtain the enviroment
        IHostEnvironment env = hostingContext.HostingEnvironment;
        //Append the files nedded for each enviroment 
        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.Local.json", optional: true, reloadOnChange: true);
    })
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService<Worker>();
        });

Then in the Worker class you could inject the configuration:

private string _pathToFile;
public Worker(IConfiguration configuration, ILogger<Worker> logger)
{
    _logger = logger;
    //Get the path needed from configuration
    _pathToFile = configuration.GetSection("PathToFile").Value;
}

The second approach is getting this by as a service argument (this is more common approach to execute a service/daemon):

internal static string PathToFile;
public static void Main(string[] args)
{
    if (args.Length < 0) throw new Exception("The service require the path to de watching file as an argument to start.");
    PathToFile = args[0];
    if (!File.Exists(PathToFile)) throw new FileNotFoundException("The file don´t exist",PathToFile);
    CreateHostBuilder(args).Build().Run();
}

Then access to it in the Worker class:

private readonly ILogger<Worker> _logger;
private string _pathToFile;

public Worker(ILogger<Worker> logger)
{
    _logger = logger;
    //Access the file loaded by argument 
    _pathToFile = Program.PathToFile;
}

Upvotes: 4

Related Questions