“ServiceCollection”不包含采用 0 个参数的构造函数

Gam*_*idi 3 c# dependency-injection

我正在尝试用 C# 创建一个 Discord 机器人,这里的代码会产生一个异常,并显示以下消息:“ServiceCollection”不包含采用 0 个参数的构造函数

_services = new ServiceCollection()
            .AddSingleton(_client)
            .AddSingleton(_commands)
            .BuildServiceProvider();
Run Code Online (Sandbox Code Playgroud)

参考资料(如果有帮助的话)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Services.Description;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
Run Code Online (Sandbox Code Playgroud)

我是编程的初学者,所以任何帮助将不胜感激!

pwr*_*imo 5

您应该将System.Web.Services.Description命名空间替换为Microsoft.Extensions.DependencyInjection

首先,您需要安装Microsoft.Extensions.DependencyInjectionnuget包,然后将其包含在命名空间引用中

using Microsoft.Extensions.DependencyInjection;
Run Code Online (Sandbox Code Playgroud)

它提供了另一个ServiceCollection类,因此您的代码不再抛出编译错误

new ServiceCollection();
Run Code Online (Sandbox Code Playgroud)