我為我的不和諧機器人編寫了一個簡單的模塊。機器人:_client = new DiscordSocketClient();_commandService = new CommandService();_serviceProvider = new ServiceCollection() .AddSingleton(_client) .AddSingleton(_commandService) .BuildServiceProvider();模塊:public class MyModule: ModuleBase<ICommandContext>{ private readonly MyService _service; public MyModule(MyService service) { _service = service; } [Command("DoStuff", RunMode = RunMode.Async)] public async Task DoStuffCmd() { await _service.DoStuff(Context.Guild, (Context.User as IVoiceState).VoiceChannel); }}模塊添加如下:await _commandService.AddModulesAsync(Assembly.GetEntryAssembly());添加模塊顯式將導致該模塊已經添加的異常,所以我假設它有效。我像這樣處理命令。// Create a number to track where the prefix ends and the command beginsint argPos = 0;// Determine if the message is a command, based on if it starts with '!' or a mention prefixif (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return;// Create a Command Contextvar context = new CommandContext(_client, message);// Execute the command. (result does not indicate a return value, // rather an object stating if the command executed successfully)var result = await _commandService.ExecuteAsync(context, argPos, _serviceProvider);該result變量總是返回Success,但DoStuffCmd在方法MyModule不會被調用。我在這里缺少什么?
1 回答

ITMISS
TA貢獻1871條經驗 獲得超8個贊
你似乎沒有注入MyService到你的ServiceCollection。
如果不注入服務,則永遠無法創建模塊,因為您將其定義為依賴項
private readonly MyService _service;
public MyModule(MyService service)
{
_service = service;
}
要解決此問題,您可以將您MyService的添加到ServiceCollection.
為此,最好創建一個IMyService(接口)并將其添加到您的注射中
_serviceProvider = new ServiceCollection()
.AddSingleton(_client)
.AddSingleton(_commandService)
.AddSingleton<IMyService, MyService>()
.BuildServiceProvider();
- 1 回答
- 0 關注
- 176 瀏覽
添加回答
舉報
0/150
提交
取消