diff --git a/Akari.Prototype.Server/Program.cs b/Akari.Prototype.Server/Program.cs index d9ded07..c5a70d7 100644 --- a/Akari.Prototype.Server/Program.cs +++ b/Akari.Prototype.Server/Program.cs @@ -1,5 +1,6 @@ using Akari.Prototype.Server.Cli.Commands; using Akari.Prototype.Server.Options; +using Akari.Prototype.Server.Utils.Extensions; using CliFx; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; @@ -74,9 +75,7 @@ namespace Akari.Prototype.Server { Startup.ConfigureStandardServices(hostContext.Configuration, services); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.AddCommandsFromThisAssembly(); }); public static IHostBuilder CreateWebHostBuilder(string[] args) => diff --git a/Akari.Prototype.Server/Utils/Extensions/IServiceCollectionExtensions.cs b/Akari.Prototype.Server/Utils/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 0000000..78a031b --- /dev/null +++ b/Akari.Prototype.Server/Utils/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,32 @@ +using CliFx; +using CliFx.Attributes; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; + +namespace Akari.Prototype.Server.Utils.Extensions +{ + public static class IServiceCollectionExtensions + { + public static IServiceCollection AddCommandsFromThisAssembly(this IServiceCollection services) => services.AddCommandsFrom(Assembly.GetCallingAssembly()); + + public static IServiceCollection AddCommandsFrom(this IServiceCollection services, Assembly assembly) + { + static bool IsCommandType(Type type) => + type.GetInterfaces().Contains(typeof(ICommand)) && + type.IsDefined(typeof(CommandAttribute)) && + !type.IsAbstract && + !type.IsInterface; + + foreach (var commandType in assembly.ExportedTypes.Where(IsCommandType)) + { + services.AddTransient(commandType); + } + + return services; + } + } +}