Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters for BackgroundService?

I read about ASP.net core 2.2 and I found reference about generic host.

I tried to create console app with backgroundService under example: https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/fundamentals/host/generic-host/samples/

var param = Console.ReadLine();

var host = new HostBuilder().ConfigureServices((hostContext, services) =>
{
   services.AddHostedService<MyCustomSerivce>();
}

The problem is how can be passed argument from command line (in my case 'param'), that will specified internal logic in particular background service.

like image 951
Kyre Avatar asked Jun 03 '19 08:06

Kyre


People also ask

Is IHostedService a singleton?

When you register implementations of IHostedService using any of the AddHostedService extension methods - the service is registered as a singleton.

What is IHostedService in .NET core?

The IHostedService interface provides a convenient way to start background tasks in an ASP.NET Core web application (in . NET Core 2.0 and later versions) or in any process/host (starting in . NET Core 2.1 with IHost ).

What are scoped Services C#?

Scoped services created in root scope are basically single-instance services, because they will be tracked and not disposed during the lifetime of the root scope. If the scoped service has dependencies, dependent services will also be created in root scope.

What is background service in C#?

BackgroundService is a base class for implementing a long running IHostedService. ExecuteAsync(CancellationToken) is called to run the background service. The implementation returns a Task that represents the entire lifetime of the background service.


1 Answers

For resolving service, you need to register the parameters into service collection.

  1. Service for storing the parameter

    public class CommandLineArgs
    {
        public string Args { get; set; }
    }
    
  2. Register the parameter

    public class Program
    {
        public static async Task Main(string[] args)
        {
            var param = Console.ReadLine();
    
            var host = new HostBuilder()
                .ConfigureHostConfiguration(configHost =>
                {
                    configHost.SetBasePath(Directory.GetCurrentDirectory());
                    configHost.AddJsonFile("hostsettings.json", optional: true);
                    configHost.AddEnvironmentVariables(prefix: "PREFIX_");
                    configHost.AddCommandLine(args);
                })
                .ConfigureAppConfiguration((hostContext, configApp) =>
                {
                    configApp.AddJsonFile("appsettings.json", optional: true);
                    configApp.AddJsonFile(
                        $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", 
                        optional: true);
                    configApp.AddEnvironmentVariables(prefix: "PREFIX_");
                    configApp.AddCommandLine(args);
                })
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddSingleton(new CommandLineArgs { Args = param });
                    services.AddHostedService<LifetimeEventsHostedService>();
                    services.AddHostedService<TimedHostedService>();
                })
                .ConfigureLogging((hostContext, configLogging) =>
                {
                    configLogging.AddConsole();
                    configLogging.AddDebug();
                })
                .UseConsoleLifetime()
                .Build();
    
            await host.RunAsync();
        }
    }
    
  3. Resolve service

    internal class TimedHostedService : IHostedService, IDisposable
    {
        private readonly ILogger _logger;
        private Timer _timer;
        private readonly IConfiguration _configuration;
        private readonly CommandLineArgs _commandLineArgs;
        public TimedHostedService(ILogger<TimedHostedService> logger
            , IConfiguration configuration
            , CommandLineArgs commandLineArgs)
        {
            _logger = logger;
            _configuration = configuration;
            _commandLineArgs = commandLineArgs;
        }       
    }
    
like image 164
Edward Avatar answered Oct 02 '22 14:10

Edward