在asp.net核心剃须刀页面中将DI与部分视图一起使用 [英] Using a DI with partial views in asp.net core razor pages

本文介绍了在asp.net核心剃须刀页面中将DI与部分视图一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下行来消耗部分视图(否则可以很好地工作;否则不使用DI):

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>))" />

LocationList的ctor接受一个 LocationDbContext 类的对象,该对象基本上是 DbContext 的子级.
但是,事实证明,我无法在局部调用中实例化 LocationDbContext .

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.

我该如何纠正?

推荐答案

我认为您应该使用

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.

我认为也可以像这样(示例)在您的视图中注入您的服务.

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)"/>

这篇关于在asp.net核心剃须刀页面中将DI与部分视图一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆