| | | 1 | | namespace Syki.Back.Configs; |
| | | 2 | | |
| | | 3 | | public static class CommandConfigs |
| | | 4 | | { |
| | 2 | 5 | | private static readonly Dictionary<string, Type> _commandTypes = []; |
| | | 6 | | |
| | | 7 | | public static void AddCommandConfigs(this WebApplicationBuilder builder) |
| | | 8 | | { |
| | 2 | 9 | | var assemblies = AppDomain.CurrentDomain.GetAssemblies() |
| | 328 | 10 | | .Where(s => s.FullName!.StartsWith("Back")) |
| | 2 | 11 | | .ToList(); |
| | | 12 | | |
| | 4 | 13 | | var commandTypes = assemblies.SelectMany(s => s.GetTypes()) |
| | 2148 | 14 | | .Where(t => t.IsAssignableTo(typeof(ICommand)) && !t.IsInterface) |
| | 2 | 15 | | .ToList(); |
| | | 16 | | |
| | 16 | 17 | | foreach (var type in commandTypes) |
| | | 18 | | { |
| | 6 | 19 | | _commandTypes[type.Name] = type; |
| | | 20 | | } |
| | | 21 | | |
| | 4 | 22 | | var handlerTypes = assemblies.SelectMany(s => s.GetTypes()) |
| | 3298 | 23 | | .Where(t => !t.IsInterface && t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == |
| | 2 | 24 | | .ToList(); |
| | | 25 | | |
| | 2 | 26 | | var handledCommandTypes = new HashSet<Type>(); |
| | | 27 | | |
| | 16 | 28 | | foreach (var type in handlerTypes) |
| | | 29 | | { |
| | 6 | 30 | | var handlerInterface = type.GetInterfaces() |
| | 12 | 31 | | .First(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler<>)); |
| | | 32 | | |
| | 6 | 33 | | handledCommandTypes.Add(handlerInterface.GetGenericArguments()[0]); |
| | 6 | 34 | | builder.Services.AddTransient(handlerInterface, type); |
| | | 35 | | } |
| | | 36 | | |
| | 2 | 37 | | var commandsWithoutHandler = commandTypes.Except(handledCommandTypes).ToList(); |
| | 2 | 38 | | if (commandsWithoutHandler.Count > 0) |
| | | 39 | | { |
| | 0 | 40 | | var names = string.Join(", ", commandsWithoutHandler.Select(t => t.Name)); |
| | 0 | 41 | | throw new InvalidOperationException($"Commands without a registered ICommandHandler<T>: {names}"); |
| | | 42 | | } |
| | 2 | 43 | | } |
| | | 44 | | |
| | | 45 | | public static Type GetCommandType(string typeName) |
| | | 46 | | { |
| | 4 | 47 | | return _commandTypes.TryGetValue(typeName, out var type) ? type |
| | 4 | 48 | | : throw new InvalidOperationException($"Command type '{typeName}' not found in registry."); |
| | | 49 | | } |
| | | 50 | | } |