我一直在通过程序类将我的依赖项注册到我的 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/