Pass Parameters to AddHostedService

Small update on Joelius answer for .Net Core 3

Given an HostedService with this constructor mixing parameters (TimeSpan) and services (ILogger<StatusService>, IHttpClientFactory)

public StatusService(
            TimeSpan cachePeriod,
            ILogger<StatusService> logger,
            IHttpClientFactory clientFactory)

You can in your Startup.cs add it to your HostedService like this :

services.AddHostedService 
    (serviceProvider => 
        new StatusService(
            TimeSpan.FromDays(1), 
            serviceProvider.GetService<ILogger<StatusService>>(), 
            serviceProvider.GetService<IHttpClientFactory>()));

While the answers above are correct, they do have the downside that you can't use DI in the Services Constructor anymore.

What I did instead was:

class Settings {
  public string Url { get; set; }
}
class SomeService : IHostedService {
  public SomeService (string instanceId, IOptionsMonitor<Settings> optionsMonitor) {
    var settings = optionsMonitor.Get(instanceId);
  }
}
services.Configure<Settings>("Instance1", (s) => s.Url = "http://google.com");
services.Configure<Settings>("Instance2", (s) => s.Url = "http://facebook.com");

services.AddSingleton<IHostedService>(x => 
 ActivatorUtilities.CreateInstance<SomeService>(x, "Instance1")
);

services.AddSingleton<IHostedService>(x => 
 ActivatorUtilities.CreateInstance<SomeService>(x, "Instance2")
);

This creates named settings for each instance and passes the named settings name to the HostedService. If you want multiple Services with the same Class and different parameters make sure to use AddSingleton instead of AddHostedService as AddHostedService will add only one instance of the same Type which will result in only one instance being started!


What Joelius answered is correct although there is another way of doing this

services.AddSingleton<IHostedService>(provider => new IntegrationService("Test"));