某些服务无法使用Blazor Server构建

发布于 2025-02-03 07:05:32 字数 553 浏览 5 评论 0原文

我有 class CustomersService:icustomersService

带有contractor:

public CustomersService(HttpClient http)
{
   this._http = http;
}

in program.cs file

builder.Services.AddScoped<ICustomersService, CustomersService>();

我应该如何重新启动/重置构造函数?

Builder.Services.AddScoped&lt; icustomersService,customersService&gt;(); 错误是:

invalidoperationException:无法解析type'system.net.http.httpclient'

i have class CustomersService : ICustomersService

with constractor:

public CustomersService(HttpClient http)
{
   this._http = http;
}

and in program.cs file:

builder.Services.AddScoped<ICustomersService, CustomersService>();

How should I reboot/reset the constructor?

builder.Services.AddScoped<ICustomersService, CustomersService>();
the error is:

InvalidOperationException: Unable to resolve service for type 'System.Net.Http.HttpClient'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

删除→记忆 2025-02-10 07:05:32

我猜想您在Blazor Server中,因为httpclient在Web Assembly中默认注册。

这是我在服务器中进行操作的方式:

// Server Side Blazor doesn't register HttpClient by default
// Thanks to Robin Sue - Suchiman https://github.com/Suchiman/BlazorDualMode
if (!services.Any(x => x.ServiceType == typeof(HttpClient))
{
     // Setup HttpClient for server side in a client side compatible fashion
     services.AddScoped<HttpClient>(s =>
    {
       // Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
       var uriHelper = s.GetRequiredService<NavigationManager>();
       return new HttpClient
       {
          BaseAddress = new Uri(uriHelper.BaseUri)
       };
   });
}

I'm guessing you're in Blazor Server as the HttpClient is registered by default in Web Assembly.

Here's how I do it in Server:

// Server Side Blazor doesn't register HttpClient by default
// Thanks to Robin Sue - Suchiman https://github.com/Suchiman/BlazorDualMode
if (!services.Any(x => x.ServiceType == typeof(HttpClient))
{
     // Setup HttpClient for server side in a client side compatible fashion
     services.AddScoped<HttpClient>(s =>
    {
       // Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
       var uriHelper = s.GetRequiredService<NavigationManager>();
       return new HttpClient
       {
          BaseAddress = new Uri(uriHelper.BaseUri)
       };
   });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文