c# - 'ServiceCollection' 不包含 'AddSingleton' 的定义

标签 c# asp.net .net dependency-injection

我一直在通过程序类将我的依赖项注册到我的 IOC 容器中,但它变得困惑了。我决定编写一个 DI 提供程序,在其中提供并注册依赖项。

在我开始解释代码之前,这是 VS 给出的完整编译错误。

'ServiceCollection' does not contain a definition for 'AddSingleton' Cannot resolve symbol 'AddSingleton'

我尽量保持简洁,在 DependencyProvider 中继承了 ServiceCollection 类

public class DependencyProvider : ServiceCollection, IDependencyProvider
{
    public DependencyProvider() : base()
    {
        Register();
    }

    public void Register()
    {
        base.AddSingleton<IContext, Context>(); // this line errors
        new ServiceCollection().AddSingleton<IContext, Context>(); // this line works
    }
}

这里是IDependencyProvider接口(interface)

public interface IDependencyProvider : IServiceCollection
{
    void Register();
}

我可以不这样做吗,还是我只是做错了什么?我真的希望这是可能的,因为解决方案看起来非常干净,建议创建一个新的 ServiceCollection 实例并为其使用该字段。

只是为了澄清错误,我无法访问 ServiceCollection 上的任何基本方法,就像这样

base.AddSingleton<IContext, Context>();

但是当创建一个内联的新实例时,这条线是有效的

new ServiceCollection().AddSingleton<IContext, Context>();

最佳答案

base 关键字不解析扩展方法。你想要做的是:

this.AddSingleton<IContext, Context>();

关于c# - 'ServiceCollection' 不包含 'AddSingleton' 的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52047779/

相关文章:

javascript - 我必须编写正则表达式,只允许 @#$% 作为特殊符号,而不允许其他符号,例如 ?><`~ 符号

C# 是否有进入 TCP 套接字编程的简单方法?

c# - 监视 Windows Phone 8.1 中的 SIM 更改

asp.net - 如何清除 Microsoft Azure 服务器上的 iis 缓存?

c# - 使用 mvc 4 中的模型根据出生日期验证年龄

c# - Linq 连接两个值

.net - 如何使用默认为 DateTimeKind.Utc 的 DateTime 值进行 DataSet.Fill?

c# - 如何检查/反汇编 Visual Studio 扩展

.net - 如何制作本地 nuget 包并在 dotnet core 中本地跨解决方案引用它们

.net - .NET 中的 "global::System"和 "System"有什么区别?