- 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
43 lines
1.4 KiB
C#
43 lines
1.4 KiB
C#
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;
|
|
}
|
|
}
|