问题描述
我一直在通过程序类将依赖项注册到我的IOC容器中,但是它很混乱。我决定写一个DI提供程序,在其中提供并注册依赖项。
I've been registering my dependencies to my IOC container via the program class, but it got messy. I decided to write a DI provider which provided and registered dependencies inside of it.
在我开始用代码解释之前,这是VS给的完整编译错误。
Before I begin explaining with code, here is the full compilation error VS gives.
我试图变得尽可能干净,在 DependencyProvider
I tried to be as clean as possible, inherting ServiceCollection class inside DependencyProvider
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接口
Here is the IDependencyProvider interface
public interface IDependencyProvider : IServiceCollection
{
void Register();
}
我可以不这样做,还是我做错了什么?我真的希望它是可行的,因为该解决方案似乎超级干净,目的是创建一个新的ServiceCollection实例并为其使用字段。
Can I not do this, or am I just doing something wrong? I really hope its possible, as the solution seems super clean, apose to creating a new instance of ServiceCollection and using the field for it.
只是为了澄清错误,我无法访问 ServiceCollection
上的任何基本方法,像这样
Just to clarify the error, I can't access any of the base methods on ServiceCollection
, like so
base.AddSingleton<IContext, Context>();
但是当创建新的实例内联时,此行有效
But this line works, when making a new instance inline
new ServiceCollection().AddSingleton<IContext, Context>();
推荐答案
基础
关键字不能解析扩展方法。您想做的是:
The base
keyword does not resolve extension methods. What you want to do is:
this.AddSingleton<IContext, Context>();
这篇关于“ ServiceCollection”不包含“ AddSingleton”的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!