37 lines
1.2 KiB
C#
37 lines
1.2 KiB
C#
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;
|
|
|
|
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();
|
|
}
|
|
}
|
|
} |