[英]Blazor service injection not working properly
I have this code in Blazor 3.0.0-preview4-19216-03 targeting a client app: 我在Blazor 3.0.0-preview4-19216-03中针对客户端应用有以下代码:
namespace BlazorShared.Services
{
public interface ILogin
{
Task<string> Login();
}
public class LoginService : ILogin
{
private HttpClient _client;
public LoginService(HttpClient client)
{
_client = client;
}
public async Task<string> Login()
{
var myclient = new HttpClient();
var responseMessage = await myclient.GetAsync("http://www.google.es");
var content = await responseMessage.Content.ReadAsStringAsync();
Debug.WriteLine(content);
return content;
}
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ILogin, LoginService>();
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
and this HTML 和这个HTML
@functions {
public async Task Submit()
{
var str = await LoginService.Login(null, null, null);
Console.WriteLine(str);
}
}
Full Razor file: https://pastebin.com/3LbQQvk0 完整的Razor文件: https : //pastebin.com/3LbQQvk0
I have tested it and the web request never gets done and I'm not able to show the service response in the client. 我已经对其进行了测试,并且Web请求从未完成,并且无法在客户端中显示服务响应。 I have tried debugging in chrome following the instructions And I see the service method is being called but the constructor of the service is not, and as I understood Blazor should inject the HttpClient.
我已经按照说明尝试在chrome中调试,而且我看到正在调用服务方法,但没有调用服务的构造函数,据我了解,Blazor应该注入HttpClient。 Any ideas what can be happening?
有什么想法会发生什么吗? Thanks.
谢谢。
The following is wrong even if it is not the culprit... In the LoginService you define an HttpClient variable into which you assign an instance of HttpClient provided by DI. 即使不是罪魁祸首,也以下内容是错误的...在LoginService中,您定义了一个HttpClient变量,您在其中分配了DI提供的HttpClient实例。 On the other hand, you define a new HttpClient object named myclient and use it in the Login method.
另一方面,您定义一个名为myclient的新HttpClient对象,并在Login方法中使用它。
You should use the object provided by DI. 您应该使用DI提供的对象。 You shouldn't yourself define HttpClient objects.
您不应该自己定义HttpClient对象。 Why ?
为什么呢 Because Blazor configure for you the HttpClient it creates.
因为Blazor为您配置了它创建的HttpClient。 For instance, setting the Document base URI, which enable your web app to be navigated as an SPA app.
例如,设置文档基础URI,使您的Web应用程序可以作为SPA应用程序进行导航。
Hope this helps... 希望这可以帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.