首页 > 解决方案 > Blazor HttpClient 注入 ViewModel 构造函数

问题描述

我正在关注下面引用的博客/文章,但无法将 HttpClient 注入我的 ViewModel。它以默认方式工作正常(剃刀文件中的@inject)。但我正在尝试注入 ViewModel。

如果我添加到如下服务,则默认注入不适用于具有@inject HttpClient 的其他剃须刀视图。

// manually add HttpClient to services.
services.AddTransient<IFetchViewModel, FetchViewModel>();

问题:

如何将默认注入的 HttpClient 注入到我的各种 ViewModel 中?

请注意,我遇到了一个例外:

WASM: Unhandled exception rendering component:
WASM: System.Reflection.TargetParameterCountException: Number of parameters specified does not match the expected number.

参考:

https://itnext.io/a-simple-mvvm-implementation-in-client-side-blazor-8c875c365435

更新

在进行建议的更改然后在调试期间深入挖掘之后,我可以看到 json 反序列化有问题。这可能是一个问题吗? https://github.com/aspnet/Blazor/issues/225

请注意,在异常堆栈跟踪的更深处,我看到以下内容:

WASM:在 SimpleJson.SimpleJson.DeserializeObject(System.String json,System.Type 类型,SimpleJson.IJsonSerializerStrategy jsonSerializerStrategy)<8f8c03446dbf45f5bbcb1e109a064f6e> 中的 <0x2ebc4f0 + 0x00068>:0 WASM:在 SimpleJson.SimpleJson.DeserializeSystem.Object[T] json) <0x2ef2490 + 0x0000a> in <8f8c03446dbf45f5bbcb1e109a064f6e>:0 WASM:
at Microsoft.JSInterop.Json.Deserialize[T] (System.String json) <0x2ef2458 + 0x00004> in <8f8c03446dbf45f5bbcb1e109a064f6e>:0 WASM:
at Microsoft.AspNetCore. Components.HttpClientJsonExtensions.GetJsonAsync[T] (System.Net.Http.HttpClient httpClient, System.String requestUri) <0x33182e0 + 0x000fa> in <13ab8f8dacb6489b93c9655168c56037>:0 WASM:
在 WebUI.Features.Fetch.FetchViewModel。LoadAsync () <0x3300de0 + 0x00102> 在 :0

更新 2

所以我现在可以确认我是在叫错树了。本质上,我有一个反序列化问题。一旦我解决了这个问题,一切正常。不确定我是否从一开始就有 DI 问题。尽管如此,我的问题现在解决了。感谢所有启发性的观点。

标签: asp.net-corerazordependency-injectionrazor-pagesblazor

解决方案


这不是您问题的真正答案;如果没有完整显示您的代码,就没有真正的答案。但是让我与以下代码片段有关;也许问题出在那儿:

// manually add HttpClient to services.
services.AddTransient<IFetchViewModel, FetchViewModel>(); 

HttpClient 服务由 Blazor 框架作为单例 (CSB) 提供。因此,您不能将 HttpClient 注入到您作为瞬态添加到应用程序中的服务中。您的服务也应该添加为单例...

希望这可以帮助...

[编辑]

How can i inject the default injected HttpClient 
to my various ViewModels?
  • 如果您的 ViewModel 是组件,您可以像这样使用 @inject 指令:

@inject HttpClient httpClient

  • 如果您的 ViewModel 是普通类 (.cs),您可以从调用组件方法传递对 HttpClient 对象的引用,或者将 HttpClient 服务注入 ViewModel 的构造函数。不要忘记在 Startup 类中添加您的服务或视图模型: services.AddSingleton<IFetchViewModel, FetchViewModel>();

再次使用AddSingleton

不,你的问题和 issue 225 无关。这个 issue 很老了,而且这个 issue 中提到的所有 bug 早在我听说 Blazor 之前就已经纠正了......

注意:异常堆栈跟踪清楚地指出了 HttpClient 是罪魁祸首的方向。执行我上面的建议,并告诉我们问题是否仍然存在。

你为什么不显示你的代码,就像其他人要求你做的那样。请查找有关如何在堆栈溢出中提问的说明。


推荐阅读