At first I'd like to say I'm new to Asp.net Core and also with concepts of dependency injection (DI). I'm reading a lot trying understand it, so I ask for patience.
I'm trying Razor Pages (not MVC) and my goal is to render to "_layout.cshtml" a partial view, in which information obtained using the Entity Framework is available on all pages.
I added the DBContext in the Startup.cs file as follows:
services.AddDbContext <AppDBContext> (options =>
options.UseSqlServer (Configuration.GetConnectionString ("AppDBContext")
And in "PageModel" for MenuPartial.cshtml.cs
public class MenuPartialModel: PageModel
{
private readonly AppDBContext _db;
public MenuPartialModel (AppDBContext db)
{
_db = db;
}
}
In the _layout.cshtm file I tried several ways to call PartialAsync with the instance of a new model:
If set new instance model like bellow I'll be using constructor without parameters, therefore the DbContext is not injected
@await Html.PartialAsync ("MenuPartial", new MenuPartialModel ())
And I also thought about using:
@await Html.PartialAsync ("MenuPartial", new MenuPartialModel (new AppDBContext ())
I believe that wouldn't be a correct approach. Because if the DbContext was injected automatically, why should I perform a new instance by passing connection parameters again?
What would be the best approach to achieve my goal? I thought about using ViewComponents, however, at first I would like to understand if there is any way to instantiate a model and use the constructor that injects the DBContext.