‘ServiceCollection’ does not contain a definition for ‘AddSingleton’

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.

Before I begin explaining with code, here is the full compilation error VS gives.

‘ServiceCollection’ does not contain a definition for ‘AddSingleton’
Cannot resolve symbol ‘AddSingleton’

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
    }
}

Here is the IDependencyProvider interface

public interface IDependencyProvider : IServiceCollection
{
    void Register();
}

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.

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>();

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The base keyword does not resolve extension methods. What you want to do is:

this.AddSingleton<IContext, Context>();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x