1
1
using System . Reflection ;
2
2
using Microsoft . Extensions . DependencyInjection ;
3
+ using Microsoft . Extensions . Hosting ;
3
4
using Microsoft . Extensions . Logging ;
4
5
using Pilgaard . CronJobs . Configuration ;
5
6
@@ -31,42 +32,46 @@ public static IServiceCollection AddCronJobs(
31
32
var cronJobOptions = new CronJobOptions ( ) ;
32
33
configuration ? . Invoke ( cronJobOptions ) ;
33
34
34
- var typesToMatch = new [ ] { typeof ( ICronJob ) } ;
35
-
36
35
foreach ( var assembly in assembliesToScan )
37
36
{
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 ) ) ) ;
54
40
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 ) ;
67
45
}
68
46
}
69
47
70
48
return services ;
71
49
}
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
+ }
72
77
}
0 commit comments