SuperMenthol
SuperMenthol

Reputation: 13

How to store and use list of interface implementations in C#?

I would like to make a quick way of registering HangFire jobs. They all implement IJob interface (which contains Task Run()). Problem is I can't get the list to accept the models created that way. Example:

Example job:

public class CheckFilesJob() : IJob
{
    async Task Run()
    {
        // do something here
    }

Model I want to use on registration:

public class JobConfiguration<T>
    where T : IJob
{
    public JobConfiguration(string key, string queueName, Expression<Func<T, Task>> jobExpression, string cronExpression)
    {
        Key = key;
        QueueName = queueName;
        JobExpression = jobExpression;
        CronExpression = cronExpression;
    }

    public string Key { get; set; }

    public string QueueName { get; set; }

    public Expression<Func<T, Task>> JobExpression { get; set; }

    public string CronExpression { get; set; }
}

How I want to instantiate the list:

new List<JobConfiguration<IJob>>
        {
            new JobConfiguration<CheckFilesJob>("Check Files",
                jobsConfiguration.Value.QueueName,
                x => x.Run(),
                jobsConfiguration.Value.CheckFilesSchedule),
            new JobConfiguration<AnotherJob>("Another Job", jobsConfiguration.Value.QueueName, x => x.Run(), jobsConfiguration.Value.AnotherJobSchedule)
        };

And how I want to use it:

    public static void HandleJobRegistration(
        this IServiceProvider serviceProvider,
        IEnumerable<JobConfiguration<IJob>> configurations)
    {
        // register each job here
    }

Problems:

  1. I can't create a list of IJob, because implementation cannot be converted to interface (CS1503).
  2. I can't seem to skip setting IJobConfiguration as generic, otherwise the jobExpression that is passed to the model belongs to the interface (not the implementation).
  3. I can't use () => new CheckFilesJob().Run(), because it will look ugly with how many services need to be provided to the job.

Tried working with both generic and non-generic class, expecting to be able to somehow provide the proper expression. Tried different ways of providing the list as an argument to the function, to no avail.

Upvotes: 0

Views: 92

Answers (0)

Related Questions