c# - 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.
解决方案
在CommandHandler
您注入 a DiscordSocketClient
,但在ConfigureServices
您注册 a DiscordShardedClient
。
您要么需要:
- 注册一个
DiscordSocketClient
,或 - 注入一个
DiscordShardedClient
.
如果您不确定要使用哪个,这里有一些文档
推荐阅读
- python-3.x - 当我使用 linux penguin 在 chromebook 上安装 python 3.9 时,我仍然看到旧版本
- react-native - 在 react native 中单击按钮上的 json 对象生成 CSV 文件
- c++ - 无限循环的编译器优化
- sql - 如何使用sql创建从ic(身份证)获取年龄的函数
- r - 在使用 group_by、quantile 和其他函数时创建新列需要很长时间并且没有给出预期的结果
- android - QT android + 远程调试
- javascript - 如何在javascript中进行正确的错误处理?
- php - 如何在 php:5.6-fpm-alpine docker 容器中启用 Memcache
- reactjs - React setState 不重新渲染组件
- entity-framework - 将模型添加到实体