So, in Razor Pages I know how I can use Dependency Injection to inject my DbContext
(for example) in the constructor to access it in the whole class by creating a global private readonly
variable.
However, let's say I have a DbManager
class that makes all the calls to the DB (to avoid making them from every Razor Page in the application), then I have to pass the context to that class, even though I'm using (at least to my knowledge) dependency injection there as well.
Shouldn't it be able to find it without actually passing it to the constructor, and isn't that the whole point of dependency injection, or am I missing something?
What is the best practice here? Just feels wrong to pass the context as a parameter! I suspect I'm doing something wrong... Am I?
CodePudding user response:
If you are not making any explicit reference calls to the context within IndexModel
then only inject the DbManager.
private readonly DbManager manager;
public IndexModel(DbManager manager) {
this.manager = manager;
}
public void OnGet() {
manager.GetStuffFromDb();
//...
}
The context will be injected into the manager when being resolved, provided it (the context) was also registered in the composition root
Reference Explicit Dependencies Principle