Add DI support for interaction commands

This commit is contained in:
Daan Boerlage 2021-10-30 14:46:23 +02:00
parent 24749d9009
commit a1893c7414
Signed by: daan
GPG key ID: FCE070E1E4956606
3 changed files with 12 additions and 10 deletions

View file

@ -1,25 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using Geekbot.Core.GlobalSettings;
using Geekbot.Core.Interactions.ApplicationCommand;
using Geekbot.Core.Interactions.Request;
using Geekbot.Core.Interactions.Response;
using Geekbot.Core.Logger;
using Microsoft.Extensions.DependencyInjection;
namespace Geekbot.Core.Interactions
{
public class InteractionCommandManager : IInteractionCommandManager
{
private readonly IServiceProvider _provider;
private readonly Dictionary<string, Type> _commands = new();
public Dictionary<string, Command> CommandsInfo { get; init; }
public InteractionCommandManager()
public InteractionCommandManager(IServiceProvider provider)
{
_provider = provider;
var interactions = Assembly.GetCallingAssembly()
.GetTypes()
.Where(type => type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(InteractionBase)))
@ -29,7 +30,7 @@ namespace Geekbot.Core.Interactions
foreach (var interactionType in interactions)
{
var instance = (InteractionBase)Activator.CreateInstance(interactionType);
var instance = (InteractionBase)ActivatorUtilities.CreateInstance(provider, interactionType) ;
var commandInfo = instance.GetCommandInfo();
_commands.Add(commandInfo.Name, interactionType);
CommandsInfo.Add(commandInfo.Name, commandInfo);
@ -39,7 +40,7 @@ namespace Geekbot.Core.Interactions
public async Task<InteractionResponse> RunCommand(Interaction interaction)
{
var type = _commands[interaction.Data.Name];
var command = (InteractionBase)Activator.CreateInstance(type);
var command = ActivatorUtilities.CreateInstance(_provider, type) as InteractionBase;
InteractionResponse response;
command.BeforeExecute();