我一直通过program类将我的依赖项注册到我的IOC容器中,但它变得混乱了。我决定编写一个DI提供程序,它在其中提供并注册依赖项。
在我开始用代码解释之前,这里是VS给出的完整的编译错误。
'ServiceCollection‘不包含'AddSingleton’的定义,无法解析符号'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接口
public interface IDependencyProvider : IServiceCollection
{
void Register();
}我可以不这样做吗,或者我只是做错了什么?我真的希望这是可能的,因为解决方案看起来非常干净,很容易创建一个新的ServiceCollection实例并使用它的字段。
为了澄清错误,我不能访问ServiceCollection上的任何基本方法,如下所示
base.AddSingleton<IContext, Context>();但是,当创建一个新的内联实例时,这行代码是有效的
new ServiceCollection().AddSingleton<IContext, Context>();发布于 2018-08-28 06:47:55
base关键字不能解析扩展方法。您想要做的是:
this.AddSingleton<IContext, Context>();https://stackoverflow.com/questions/52047779
复制相似问题