【发布时间】:2020-01-22 14:38:54
【问题描述】:
我的应用程序中有一个 blazor 组件:
public class IndexComponent : ComponentBase
{
public string ContentRoot { get; set; }
public string WebRoot { get; set; }
private IHostingEnvironment HostingEnvironment;
public IndexComponent(IHostingEnvironment hostingEnvironment)
{
HostingEnvironment = hostingEnvironment;
}
protected override async Task OnInitAsync()
{
//Some Code Here
}
}
我正在尝试在我的应用中使用 DI,例如 IHostingEnvironment。
这里的代码没有给出编译时错误,但是当我运行它而不是这个剃须刀的代码隐藏文件(Index.razor.g.cs 文件):
public class Index : IndexComponent
在这一行它说:
没有给出与所需形式相对应的参数 IndexComponent.IndexComponent的参数hostingEnvironment
这可以通过在 Razor 文件中使用 @inject IHostingEnvironment 来解决,但我正在将我的功能块从 Razor 移动到 IndexComponent.cs 文件,所以需要它。
这两种方式都不适用:
[Inject]
IHostingEnvironment HostingEnvironment
这里有什么用?
注意:不使用 ViewModel
更新 1
在 StartUp.cs 中添加命名空间
using Microsoft.AspNetCore.Hosting.Internal;
然后
services.AddSingleton<IHostingEnvironment>(new HostingEnvironment());
它现在可以在客户端项目上注册 IHostingEnvironment,但它的属性(contentrootpath 和 webrootpath)没有值。
这里只有一件事是 EnvironmentName 并且它的值始终是 Production ,
【问题讨论】:
-
你的代码没有错。看起来您正在某处手动创建一些新的索引或索引组件。
-
@daniherrera 是的,这是将代码与另一个文件中的 html 标记分离并继承该类文件中的 ComponentBase 的标准方法,直到我们在 ASP.Net Blazor 中使用依赖注入。它给出了错误
-
我在代码组件上广泛使用 DI,没有任何问题。您是否尝试在某个地方手动创建组件的新实例?这种错误(缺少 DI 元素)通常是在运行时而不是在编译时引发的。
-
不,没有使用new关键字来创建组件实例
-
@daniherrera 请参阅更新 1
标签: c# asp.net-core blazor blazor-client-side