Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
NielsPilgaard committed Apr 23, 2022
2 parents be8ba77 + 40fed73 commit b9b2874
Showing 1 changed file with 35 additions and 30 deletions.
65 changes: 35 additions & 30 deletions src/Pilgaard.CronJobs/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Pilgaard.CronJobs.Configuration;

Expand Down Expand Up @@ -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<IServiceScopeFactory>(),
serviceProvider.GetRequiredService<ILogger<CronBackgroundService>>(),
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<CronJobOptions>? configuration)
{
services.AddSingleton<IHostedService>(serviceProvider =>
new CronBackgroundService((ICronJob)serviceProvider.GetRequiredService(@class),
serviceProvider.GetRequiredService<IServiceScopeFactory>(),
serviceProvider.GetRequiredService<ILogger<CronBackgroundService>>(),
configuration));
}
}

0 comments on commit b9b2874

Please sign in to comment.