- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我一直在通过程序类将我的依赖项注册到我的 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/
我正在使用这种方法构建服务实现: 我正在使用 Microsoft.Extensions.DependencyInjection 并尝试实现以下目标: 创建本地 ServiceCollection 并保
有没有办法实现下一个行为? public static void Configure(IServiceCollection services) { services.AddScoped(typ
我正在为 ServiceCollection 编写自己的扩展方法来注册我的模块的类型,并且我需要从集合中访问 IConfiguration 实例来注册我的选项。 扩展方法 public static
是否有通过包含接口(interface) -> 类映射 的 JSON 文件在 .NET Core 2.0 中配置依赖项注入(inject)的示例?例如 var someServiceConfigBui
我正在制作 fixture到我的tests . 在我的 FixtureFactory我自己做 ServiceCollection : private static ServiceCollect
我一直在通过程序类将我的依赖项注册到我的 IOC 容器中,但它变得困惑了。我决定编写一个 DI 提供程序,在其中提供并注册依赖项。 在我开始解释代码之前,这是 VS 给出的完整编译错误。 'Servi
我目前正在尝试创建一个 Logger,以便我可以将其注入(inject)单元测试。我正在关注 https://stackoverflow.com/a/43425633/1057052 ,它曾经有效!然
我了解如何为 ASP.NET Core 注册依赖项,以及构造函数注入(inject)如何为我的 Controller 工作(我有那个工作)。是否所有的东西都必须通过构造函数传递,然后显式地传递给那些构
我想将 Autofac 添加到 .Net Core 应用程序。我已尝试完成 Autofac:Getting started tutorial 中的所有步骤,我安装了 Autofac.Extension
有没有一种方法可以在 .net core 的标准 Microsoft.Extensions.DependencyInjection.ServiceCollection 库中配置依赖注入(inject)
我的 asp.net core 2.x 应用程序有典型的日志记录要求: 在生产中使用应用洞察力, 在开发环境中控制台和调试记录器 根据类别和日志级别设置一些过滤器 现在我看到至少三个不同的 API 来
我们有带有标准 Microsoft.Extensions.DependencyInjection 的 ASP.NET Core 解决方案,并且需要根据配置设置注册某些控件。 一些继承自 Control
我正在将我的 Web 应用程序从 ASP.NET Core RC1 迁移到 RC2。在 RC2 中,IServiceCollection 不再有 AddInstance 方法。如何注册配置? 这是在
我是一名优秀的程序员,十分优秀!