feat: CodeGenerator-Service mit Konfigurationsunterstützung implementiert
- CodeGenerator-Service erstellt, der zufällige Codes basierend auf einem konfigurierbaren Zeichensatz generiert. - IOptions<CodeGeneratorConfig> für DI-Injektion der Konfigurationseinstellungen integriert. - Lazy-Initialisierung für statische Instanz des CodeGenerators hinzugefügt. - Validierung hinzugefügt, um sicherzustellen, dass die Code-Länge größer als null ist. - Geplante zukünftige Verbesserung: Random als Singleton injizieren, um die Multithreading-Performance zu verbessern.
This commit is contained in:
37
EnvelopeGenerator.Application/Services/CodeGenerator.cs
Normal file
37
EnvelopeGenerator.Application/Services/CodeGenerator.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using EnvelopeGenerator.Application.Configurations;
|
||||
using EnvelopeGenerator.Application.Contracts;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Text;
|
||||
|
||||
namespace EnvelopeGenerator.Application.Services
|
||||
{
|
||||
public class CodeGenerator : ICodeGenerator
|
||||
{
|
||||
public static Lazy<CodeGenerator> LazyStatic => new(() => new CodeGenerator(Options.Create<CodeGeneratorConfig>(new())));
|
||||
|
||||
public static CodeGenerator Static => LazyStatic.Value;
|
||||
|
||||
private readonly string _charPool = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
public CodeGenerator(IOptions<CodeGeneratorConfig> options)
|
||||
{
|
||||
_charPool = options.Value.CharPool;
|
||||
}
|
||||
|
||||
public string GenerateCode(int length)
|
||||
{
|
||||
//TODO: Inject Random as a singleton to support multithreading to improve performance.
|
||||
Random random = new();
|
||||
|
||||
if (length <= 0)
|
||||
throw new ArgumentException("Password length must be greater than 0.");
|
||||
|
||||
var passwordBuilder = new StringBuilder(length);
|
||||
|
||||
for (int i = 0; i < length; i++)
|
||||
passwordBuilder.Append(_charPool[random.Next(_charPool.Length)]);
|
||||
|
||||
return passwordBuilder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user