Skip to content

Commit edbe949

Browse files
committed
Feat: AddOneTimeDataSeeder overload to setup seeder directly
1 parent 392d77a commit edbe949

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

src/CodeOfChaos.Types.DataSeeder/ServiceCollectionExtensions.cs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
// Imports
33
// ---------------------------------------------------------------------------------------------------------------------
44
using CodeOfChaos.Types;
5+
using Microsoft.Extensions.DependencyInjection.Extensions;
6+
using Microsoft.Extensions.Hosting;
57

68
// ReSharper disable once CheckNamespace
79
namespace Microsoft.Extensions.DependencyInjection;
@@ -10,10 +12,28 @@ namespace Microsoft.Extensions.DependencyInjection;
1012
// ---------------------------------------------------------------------------------------------------------------------
1113
public 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

Comments
 (0)