Skip to content

Multiple instances registrations #13

@paulowirth

Description

@paulowirth

Hello,

I am here to request support for registering multiple instances of the same service, i.e. instead of creating one class for each Cron Expression, as mentioned in your original post, it is desirable to register as indicated by the code below

appsettings.json or equivalent

"CronServiceConfiguration": {
 "ServiceSchedules": 
      [
        "0 55-59/1 21 * * *",
        "0/5 * 22 * * *"
      ]
}

Startup.cs class or equivalent

// Cron Jobs
IList<string> serviceSchedules = configuration.GetSection("CronServiceConfiguration:ServiceSchedules").Bind(serviceSchedules);

ArgumentNullException.ThrowIfNull(serviceSchedules);
            
foreach (string schedule in serviceSchedules)
{
    services
        .RegisterCronServiceInstance<CronService>(cronConfiguration =>
        {
            cronConfiguration.TimeZoneInfo = TimeZoneInfo.Local;
            cronConfiguration.CronExpression = schedule;
            cronConfiguration.CronFormat = CronFormat.IncludeSeconds;
        });
}

As per Microsoft's recommendation, which you may read here, instead of calling

services.AddHostedService<TCronService>();

We would register each instance using

services.AddSingleton<ICronConfiguration<TCronService>>(cronConfiguration);
services.AddSingleton<IHostedService, TCronService>();

However, the main problem lies in the configurations.
The classes are registered ok as singletons, but they only read the latest registered configuration.
How can we ensure that each instance has the current registered configuration?

Any help would be appreciated.
Kind regards,
Paulo

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions