我的应用程序中有一个 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 ,