6

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

4

3 回答 3

11

更新:

错误来自 WebAssembly,因此它是一个客户端应用程序。客户端上没有 HostingEnvironment,因此该服务未注册。如果是的话就没有用了。

所以,退后一步:为什么(你认为)你需要它?


您应该使其成为受保护的或公共的读/写属性:

// in IndexComponent
[Inject]
protected IHostingEnvironment HostingEnvironment { get; set; }

并删除构造函数参数。

旁注:IHostingEnvironment标记为已过时。

于 2019-09-22T12:03:03.277 回答
3

事实证明,对于 Blazor,您需要一个稍微不同的界面,即IWebAssemblyHostEnvironment.

从此文档中,您应该注入的是:

@inject IWebAssemblyHostEnvironment HostEnvironment
于 2021-04-21T10:48:00.213 回答
1

从这个评论:

WASM:System.InvalidOperationException:无法为类型“JewelShut.Client.Pages.Index”的属性“HostingEnvironment”提供值。没有“Microsoft.AspNetCore.Hosting.IHostingEnvironment”类型的注册服务

我猜这是客户端Blazor 应用程序。(如果我的猜测有误,我深表歉意。)。在客户端 Blazor 上IHostingEnvironment,默认情况下未在 DI 容器中注册。错误仍然表明您尝试注入的服务未注册。要注册服务:

在 Startup.cs 中:

public void ConfigureServices(IServiceCollection services)
{
    //few sample for you
    services.AddScoped<AuthenticationStateProvider, ApiAuthenticationStateProvider>();
    services.AddAuthorizationCore();

    //register the required services
    //services.Add...
}

如果注入的服务按照@Henk Holterman 建议的方式注册是正确的答案。

Di in blazor

于 2019-09-22T12:35:20.160 回答