From 024a1e1f65ec18a1ddef88bb91e8e0aaae38ae74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niels=20Pilgaard=20Gr=C3=B8ndahl?= Date: Sat, 23 Apr 2022 22:19:02 +0200 Subject: [PATCH] made sure every ICronJob found gets hosted Also rewrote assembly scanning to be cleaner, hopefully --- .../Extensions/ServiceCollectionExtensions.cs | 65 ++++++++++--------- 1 file changed, 35 insertions(+), 30 deletions(-) diff --git a/src/Pilgaard.CronJobs/Extensions/ServiceCollectionExtensions.cs b/src/Pilgaard.CronJobs/Extensions/ServiceCollectionExtensions.cs index 52a76ba..c8d8a12 100644 --- a/src/Pilgaard.CronJobs/Extensions/ServiceCollectionExtensions.cs +++ b/src/Pilgaard.CronJobs/Extensions/ServiceCollectionExtensions.cs @@ -1,5 +1,6 @@ using System.Reflection; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Pilgaard.CronJobs.Configuration; @@ -31,42 +32,46 @@ public static IServiceCollection AddCronJobs( var cronJobOptions = new CronJobOptions(); configuration?.Invoke(cronJobOptions); - var typesToMatch = new[] { typeof(ICronJob) }; - foreach (var assembly in assembliesToScan) { - var classes = assembly.ExportedTypes.Where(type => !type.IsAbstract && type.GetInterfaces().Any()); - foreach (var @class in classes) - { - foreach (var @interface in @class.GetInterfaces()) - { - foreach (var typeToMatch in typesToMatch) - { - if (@interface != typeToMatch) - { - continue; - } - - services.Add(new ServiceDescriptor( - typeToMatch, - @class, - cronJobOptions.ServiceLifetime)); + var implementsICronJob = assembly.ExportedTypes.Where(type => + !type.IsAbstract && + type.GetInterfaces().Contains(typeof(ICronJob))); - services.Add(new ServiceDescriptor( - @class, - @class, - cronJobOptions.ServiceLifetime)); - - services.AddHostedService(serviceProvider => - new CronBackgroundService((ICronJob)serviceProvider.GetRequiredService(@class), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService>(), - configuration)); - } - } + foreach (var cronJob in implementsICronJob) + { + RegisterCronJob(services, cronJobOptions, cronJob); + AddHostedCronBackgroundService(services, cronJob, configuration); } } return services; } + + private static void RegisterCronJob(IServiceCollection services, + CronJobOptions cronJobOptions, + Type concreteClass) + { + services.Add(new ServiceDescriptor( + typeof(ICronJob), + concreteClass, + cronJobOptions.ServiceLifetime)); + + services.Add(new ServiceDescriptor( + concreteClass, + concreteClass, + cronJobOptions.ServiceLifetime)); + } + + private static void AddHostedCronBackgroundService( + IServiceCollection services, + Type @class, + Action? configuration) + { + services.AddSingleton(serviceProvider => + new CronBackgroundService((ICronJob)serviceProvider.GetRequiredService(@class), + serviceProvider.GetRequiredService(), + serviceProvider.GetRequiredService>(), + configuration)); + } } \ No newline at end of file