Refactor and enhance DependencyInjection class

Organized the `DependencyInjection` class into regions for better code structure: `Required Services`, `Configuration`, `LuckyPennySoftwareLicenseKey`, and `ConfigureRecActions`.

Added `_requiredServices` dictionary to track the configuration status of required services. Updated `LuckyPennySoftwareLicenseKey` to include a null check before marking it as configured.

Moved `_configActions` to the `Configuration` region and added `ApplyConfigurations` to process queued configuration actions.

Enhanced `ConfigureRecActions` to prevent duplicate configurations by throwing an `InvalidOperationException` if already configured.

These changes improve code readability, maintainability, and robustness.
This commit is contained in:
tekh 2025-11-27 10:09:20 +01:00
parent 2a9b52ebe1
commit 8aa43db909

View File

@ -35,8 +35,8 @@ public static class DependencyInjection
public class ConfigurationOptions
{
private readonly Queue<Action<IServiceCollection>> _configActions = new();
#region Required Services
private readonly Dictionary<string, bool> _requiredServices = new()
{
{ nameof(ConfigureRecActions), false },
@ -51,7 +51,11 @@ public static class DependencyInjection
if (missingServices.Any())
throw new InvalidOperationException($"The following required services were not configured: {string.Join(", ", missingServices)}");
}
#endregion Required Services
#region Configuration
private readonly Queue<Action<IServiceCollection>> _configActions = new();
internal void ApplyConfigurations(IServiceCollection services)
{
while (_configActions.Count > 0)
@ -60,7 +64,9 @@ public static class DependencyInjection
action(services);
}
}
#endregion Configuration
#region LuckyPennySoftwareLicenseKey
private string? _luckyPennySoftwareLicenseKey;
public string? LuckyPennySoftwareLicenseKey
@ -69,22 +75,34 @@ public static class DependencyInjection
set
{
_luckyPennySoftwareLicenseKey = value;
_requiredServices[nameof(LuckyPennySoftwareLicenseKey)] = true;
if (value is not null)
_requiredServices[nameof(LuckyPennySoftwareLicenseKey)] = true;
}
}
#endregion LuckyPennySoftwareLicenseKey
#region ConfigureRecActions
public ConfigurationOptions ConfigureRecActions(Action<RecActionOptions> configure)
{
_configActions.Enqueue(services => services.Configure(configure));
if(_requiredServices[nameof(ConfigureRecActions)])
throw new InvalidOperationException("RecActionOptions have already been configured.");
_requiredServices[nameof(ConfigureRecActions)] = true;
return this;
}
public ConfigurationOptions ConfigureRecActions(IConfiguration configuration)
{
_configActions.Enqueue(services => services.Configure<RecActionOptions>(configuration));
if (_requiredServices[nameof(ConfigureRecActions)])
throw new InvalidOperationException("RecActionOptions have already been configured.");
_requiredServices[nameof(ConfigureRecActions)] = true;
return this;
}
#endregion ConfigureRecActions
}
}