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?
CodePudding user response:
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://docs.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
}