首页 > 解决方案 > DiscordBot:Unable to resolve service for type 'Discord.WebSocket.DiscordSocketClient' while attempting to activate 'LockDocler.Services.CommandHandler

问题描述

Im trying to make bot for discord on Discord.net for first time.

Here's my code.

   class StartUp
{
    public IConfigurationRoot Configuration { get; }

    public StartUp(string[] args)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddYamlFile("_config.yml");
        Configuration = builder.Build();
    }
    public static async Task RunAsync(string[] args)
    {
        var startup = new StartUp(args);
        await startup.RunAsync(); 
    }

    public async Task RunAsync()
    {
        var services = new ServiceCollection();
        ConfigureServices(services);

        var provider = services.BuildServiceProvider();
        provider.GetRequiredService<CommandHandler>();

        await provider.GetRequiredService<StartUpService>().StartAsync();
        await Task.Delay(-1);
    }
    private void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(new DiscordShardedClient(new DiscordSocketConfig
        {
            LogLevel = LogSeverity.Verbose,
            MessageCacheSize = 1000

        }))
        .AddSingleton(new CommandService(new CommandServiceConfig
        {
            LogLevel = Discord.LogSeverity.Verbose,
            DefaultRunMode = RunMode.Async,
            CaseSensitiveCommands = false
        }))
        .AddSingleton<CommandHandler>()
        .AddSingleton<StartUpService>()
        .AddSingleton(Configuration);
    }
}

}

problem on string provider.GetRequiredService<CommandHandler>();

Code of CommandHandler

class CommandHandler
{
    public static IServiceProvider _provider;
    public static DiscordSocketClient _discord;
    public static CommandService commands;
    public static IConfigurationRoot _config;

    public CommandHandler(DiscordSocketClient discord, CommandService command, IConfigurationRoot conf, IServiceProvider provider)
    {
        _provider = provider;
        _config = conf;
        _discord = discord;
        commands = command;


        _discord.Ready += OnReady;
    }

    private Task OnReady()
    {
        Console.WriteLine($"been connected as user {_discord.CurrentUser.Username}#{_discord.CurrentUser.Discriminator}");
        return Task.CompletedTask;
    }
}

Exeption: "Unable to resolve service for type 'Discord.WebSocket.DiscordSocketClient' while attempting to activate 'LockDocler.Services.CommandHandler". I have no idea to solve this, thanks right away.

标签: c#discord.net

解决方案


CommandHandler您注入 a DiscordSocketClient,但在ConfigureServices您注册 a DiscordShardedClient

您要么需要:

  1. 注册一个DiscordSocketClient,或
  2. 注入一个DiscordShardedClient.

如果您不确定要使用哪个,这里有一些文档


推荐阅读