Skip to content

Commit 40fed73

Browse files
Merge pull request #3 from NielsPilgaard/allow-multiple-cronjobs
Made sure every ICronJob found gets hosted
2 parents 24d20ad + 024a1e1 commit 40fed73

File tree

1 file changed

+35
-30
lines changed

1 file changed

+35
-30
lines changed
Lines changed: 35 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Reflection;
22
using Microsoft.Extensions.DependencyInjection;
3+
using Microsoft.Extensions.Hosting;
34
using Microsoft.Extensions.Logging;
45
using Pilgaard.CronJobs.Configuration;
56

@@ -31,42 +32,46 @@ public static IServiceCollection AddCronJobs(
3132
var cronJobOptions = new CronJobOptions();
3233
configuration?.Invoke(cronJobOptions);
3334

34-
var typesToMatch = new[] { typeof(ICronJob) };
35-
3635
foreach (var assembly in assembliesToScan)
3736
{
38-
var classes = assembly.ExportedTypes.Where(type => !type.IsAbstract && type.GetInterfaces().Any());
39-
foreach (var @class in classes)
40-
{
41-
foreach (var @interface in @class.GetInterfaces())
42-
{
43-
foreach (var typeToMatch in typesToMatch)
44-
{
45-
if (@interface != typeToMatch)
46-
{
47-
continue;
48-
}
49-
50-
services.Add(new ServiceDescriptor(
51-
typeToMatch,
52-
@class,
53-
cronJobOptions.ServiceLifetime));
37+
var implementsICronJob = assembly.ExportedTypes.Where(type =>
38+
!type.IsAbstract &&
39+
type.GetInterfaces().Contains(typeof(ICronJob)));
5440

55-
services.Add(new ServiceDescriptor(
56-
@class,
57-
@class,
58-
cronJobOptions.ServiceLifetime));
59-
60-
services.AddHostedService(serviceProvider =>
61-
new CronBackgroundService((ICronJob)serviceProvider.GetRequiredService(@class),
62-
serviceProvider.GetRequiredService<IServiceScopeFactory>(),
63-
serviceProvider.GetRequiredService<ILogger<CronBackgroundService>>(),
64-
configuration));
65-
}
66-
}
41+
foreach (var cronJob in implementsICronJob)
42+
{
43+
RegisterCronJob(services, cronJobOptions, cronJob);
44+
AddHostedCronBackgroundService(services, cronJob, configuration);
6745
}
6846
}
6947

7048
return services;
7149
}
50+
51+
private static void RegisterCronJob(IServiceCollection services,
52+
CronJobOptions cronJobOptions,
53+
Type concreteClass)
54+
{
55+
services.Add(new ServiceDescriptor(
56+
typeof(ICronJob),
57+
concreteClass,
58+
cronJobOptions.ServiceLifetime));
59+
60+
services.Add(new ServiceDescriptor(
61+
concreteClass,
62+
concreteClass,
63+
cronJobOptions.ServiceLifetime));
64+
}
65+
66+
private static void AddHostedCronBackgroundService(
67+
IServiceCollection services,
68+
Type @class,
69+
Action<CronJobOptions>? configuration)
70+
{
71+
services.AddSingleton<IHostedService>(serviceProvider =>
72+
new CronBackgroundService((ICronJob)serviceProvider.GetRequiredService(@class),
73+
serviceProvider.GetRequiredService<IServiceScopeFactory>(),
74+
serviceProvider.GetRequiredService<ILogger<CronBackgroundService>>(),
75+
configuration));
76+
}
7277
}

0 commit comments

Comments
 (0)