22// Imports
33// ---------------------------------------------------------------------------------------------------------------------
44using CodeOfChaos . Types ;
5+ using Microsoft . Extensions . DependencyInjection . Extensions ;
6+ using Microsoft . Extensions . Hosting ;
57
68// ReSharper disable once CheckNamespace
79namespace Microsoft . Extensions . DependencyInjection ;
@@ -10,10 +12,28 @@ namespace Microsoft.Extensions.DependencyInjection;
1012// ---------------------------------------------------------------------------------------------------------------------
1113public static class ServiceCollectionExtensions {
1214 public static IServiceCollection AddOneTimeDataSeeder < TDataSeeder > ( this IServiceCollection services )
13- where TDataSeeder : class , IDataSeederService
15+ where TDataSeeder : class , IDataSeederService , IHostedService
1416 => services . AddHostedService < TDataSeeder > ( ) ;
1517
1618 public static IServiceCollection AddOneTimeDataSeeder < TDataSeeder > ( this IServiceCollection services , Func < IServiceProvider , TDataSeeder > implementationFactory )
17- where TDataSeeder : class , IDataSeederService
19+ where TDataSeeder : class , IDataSeederService , IHostedService
1820 => services . AddHostedService ( implementationFactory ) ;
21+
22+ public static IServiceCollection AddOneTimeDataSeeder < TDataSeeder > ( this IServiceCollection services , Action < TDataSeeder > configure )
23+ where TDataSeeder : class , IDataSeederService , IHostedService {
24+
25+ services . TryAddEnumerable (
26+ ServiceDescriptor . Singleton < IHostedService , TDataSeeder > ( provider
27+ => {
28+ var seeder = ActivatorUtilities . CreateInstance < TDataSeeder > ( provider ) ;
29+ configure ( seeder ) ;
30+ return seeder ;
31+ }
32+ )
33+ ) ;
34+ return services ;
35+ }
36+
37+ public static IServiceCollection AddOneTimeDataSeeder ( this IServiceCollection services , Action < OneTimeDataSeederService > configure )
38+ => AddOneTimeDataSeeder < OneTimeDataSeederService > ( services , configure ) ;
1939}
0 commit comments