Blazor 组件文件中的依赖项注入

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


波斯汪
浏览 104回答 3
3回答

HUWWW

更新:该错误来自 WebAssembly,因此它是一个客户端应用程序。客户端上没有 HostingEnvironment,因此服务未注册。如果是的话那就没什么用了。所以,退一步:为什么(你认为)你需要它?您应该将其设为受保护或公共读/写属性:// in IndexComponent[Inject]protected IHostingEnvironment HostingEnvironment { get; set; }并删除构造函数参数。旁注:IHostingEnvironment 已标记为已过时。

Smart猫小萌

事实证明,对于 Blazor,您需要一个稍微不同的界面,即IWebAssemblyHostEnvironment。从此文档中,您应该注入的是:@inject IWebAssemblyHostEnvironment HostEnvironment

慕标琳琳

来自这个评论:WASM:System.InvalidOperationException:无法为属性“HostingEnvironment”提供值;在类型“JewelShut.Client.Pages.Index”上。没有类型为“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...}
打开App,查看更多内容
随时随地看视频慕课网APP