asp.net-coredependency-injectioninversion-of-controlrazor-pagespartial-views

Using a DI with partial views in asp.net core razor pages


A partial view (working completely fine otherwise; when not using DI that is) is being consumed using the following line:

<partial
    name="Partials/SelectLoc"
    model="new Partials.SelectLocModel(new HttpClient(), (<this is the part with DI>))" />

The ctor for LocationList takes an object of LocationDbContext class which is basically a child of DbContext.
However, as it turns out, I am unable to instantiate the LocationDbContext in the call to the partial.

How do I correct this?


Solution

  • I think you should use View components instead of partial view.A view component is like a partial view that has a model, a view, and a controller.You can directly inject Dbcontext into it.

    public class YourViewComponent : ViewComponent
    {
    private readonly LocationDbContext dbContext;
    
    public YourViewComponent (LocationDbContext dbContext)
    {
        this.dbContext = dbContext;
    }
    
    public async Task<IViewComponentResult> InvokeAsync()
    {
     //...
    }
    }
    

    About the details you can see the doc or this thread.

    Edit:

    I think there also can Inject your services in your view like this(example).

    @inject System.Net.Http.HttpClient httpClient
    @inject WebApplication150.Data.WebApplication150Context context
    
    <partial name="Partials/SelectLoc"
         model="new Pages.SelectLocModelModel(httpClient,context)"/>