44 lines
1.5 KiB
C#
44 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using Svrnty.CQRS.Abstractions.Discovery;
|
|
|
|
namespace Svrnty.CQRS.Discovery;
|
|
|
|
public sealed class CommandDiscovery : ICommandDiscovery
|
|
{
|
|
private readonly List<ICommandMeta> _commandMetas;
|
|
private readonly Dictionary<string, ICommandMeta> _commandsByName;
|
|
private readonly Dictionary<Type, ICommandMeta> _commandsByType;
|
|
|
|
public CommandDiscovery(IEnumerable<ICommandMeta> commandMetas)
|
|
{
|
|
// Materialize the enumerable to a list once
|
|
_commandMetas = commandMetas.ToList();
|
|
|
|
// Build lookup dictionaries for O(1) access
|
|
_commandsByName = new Dictionary<string, ICommandMeta>(_commandMetas.Count);
|
|
_commandsByType = new Dictionary<Type, ICommandMeta>(_commandMetas.Count);
|
|
|
|
foreach (var meta in _commandMetas)
|
|
{
|
|
_commandsByName[meta.Name] = meta;
|
|
_commandsByType[meta.CommandType] = meta;
|
|
}
|
|
}
|
|
|
|
public IEnumerable<ICommandMeta> GetCommands() => _commandMetas;
|
|
|
|
public ICommandMeta FindCommand(string name) =>
|
|
_commandsByName.TryGetValue(name, out var meta) ? meta : null;
|
|
|
|
public ICommandMeta FindCommand(Type commandType) =>
|
|
_commandsByType.TryGetValue(commandType, out var meta) ? meta : null;
|
|
|
|
public bool CommandExists(string name) =>
|
|
_commandsByName.ContainsKey(name);
|
|
|
|
public bool CommandExists(Type commandType) =>
|
|
_commandsByType.ContainsKey(commandType);
|
|
}
|