refactor: Extract ProfileWorker into modular components
- Create ProfileWorker namespace with 4 separate components - ProfileWorker.cs: BackgroundService orchestrator with IOptions support - ProfileWorkerOptions.cs: Configuration model with validation - ProfileCache.cs: Thread-safe cache using composition pattern - DependencyInjection.cs: Service registration with IValidateOptions Benefits: - Separation of concerns (orchestration, config, state, DI) - IOptions pattern for appsettings.json configuration - Startup validation for configuration errors - Better testability and maintainability
This commit is contained in:
42
ECMJobRunner.WebCron/ProfileWorker/DependencyInjection.cs
Normal file
42
ECMJobRunner.WebCron/ProfileWorker/DependencyInjection.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ECMJobRunner.WebCron.ProfileWorker;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static IServiceCollection AddProfileWorker(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
// Configure ProfileWorker options from appsettings.json
|
||||
services.Configure<ProfileWorkerOptions>(
|
||||
configuration.GetSection(ProfileWorkerOptions.SectionName));
|
||||
|
||||
// Validate options at startup
|
||||
services.AddSingleton<IValidateOptions<ProfileWorkerOptions>, ProfileWorkerOptionsValidator>();
|
||||
|
||||
services.AddHostedService<ProfileWorker>();
|
||||
services.AddSingleton<ProfileCache>();
|
||||
services.AddScoped<ProfileWork>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates ProfileWorkerOptions configuration at startup.
|
||||
/// </summary>
|
||||
internal class ProfileWorkerOptionsValidator : IValidateOptions<ProfileWorkerOptions>
|
||||
{
|
||||
public ValidateOptionsResult Validate(string? name, ProfileWorkerOptions options)
|
||||
{
|
||||
if (options.IntervalMS <= 0)
|
||||
{
|
||||
return ValidateOptionsResult.Fail("ProfileWorker:IntervalMs must be greater than 0");
|
||||
}
|
||||
|
||||
if (options.IntervalMS < 100)
|
||||
{
|
||||
return ValidateOptionsResult.Fail("ProfileWorker:IntervalMs should be at least 100ms to avoid excessive CPU usage");
|
||||
}
|
||||
|
||||
return ValidateOptionsResult.Success;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user