0

I'm using MongoDB in my project, I have created a DB context like this:

public class PortfolioDbContext
{
    public readonly IMongoCollection<PortfolioData> _portfolioCollection;

    public PortfolioDbContext()
    {
        var client = new MongoClient("mongodb://localhost:27017");
        _portfolioCollection = client.GetDatabase("portfolioServiceDb").GetCollection<PortfolioData>("Portfolios");
    }
}

I was to inject it into my repository class:

    public PortfolioDbContext _db;

    public DataService(PortfolioDbContext _db)
    {
        _db = this._db;
    }

but db returns null, I thought I need to register it in my startup:

 services.AddSingleton<PortfolioDbContext>();

but I'm still getting null, any idea why?

1
  • Try this._db = _db in the constructor of DataService. Commented Oct 30, 2021 at 18:12

1 Answer 1

2

The error is in the constructor of DataService. Your are assigning this._db (the variable of the class) to _db (the argument of the constructor), instead of the other way around. As the default of public PortfolioDbContext _db is null and you are never assigning a different value to it, it remains null.

The coding guidelines from Microsoft https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions recommends using camel case with a _ prefix for private variables in a class and method parameters with camel case (without underline). This helps preventing issues like this.

Your DataService could look like this:

public class DataService
{
    private PortfolioDbContext _db;

    public DataService(PortfolioDbContext db)
    {
        _db = db;
    }

    // ... some more methods
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.