“ ServiceCollection”不包含“ AddSingleton”的定义

编程入门 行业动态 更新时间:2024-10-17 09:44:31
本文介绍了“ ServiceCollection”不包含“ AddSingleton”的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

'ServiceCollection'不包含'AddSingleton'的定义无法解析符号'AddSingleton'

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

我试图变得尽可能干净,在 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”的定义

本文发布于:2023-11-13 14:56:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584637.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不包含   定义   ServiceCollection   AddSingleton

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!