我正在使用WebAssembly 6.0开发一个Blazor的.NET应用程序。
我正在使用MediatR请求和处理程序。
public class DummyRequest : IRequest<string>
{
public Guid Test { get; } = new Guid("e9f41a5d-5da6-4aad-b118-83476b7f40f4");
}
public class DummyHandler : IRequestHandler<DummyRequest, string>
{
private readonly HttpClient _httpClient;
public DummyHandler(HttpClient httpClient)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}
public async Task<string> Handle(DummyRequest request, CancellationToken cancellationToken)
{
// This should be the value configured in Program.cs
string baseAddress = _httpClient.BaseAddress?.AbsoluteUri ?? string.Empty;
// But it's always blank, so we can't make any calls with the HttpClient
await Task.CompletedTask;
return "foobar";
}
}
我在Program.cs中为每个请求处理程序配置不同的MediatR,然后添加MediatR:
builder.Services.AddHttpClient<DummyHandler>((client) => { client.BaseAddress = new Uri("https://api.somewhere.com"); });
builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
我还尝试逆转这些调用,以便首先添加MediatR,然后为DummyHandler类型注册HttpClient。
在运行时,在实例化该Handler之后,它应该有一个_httpClient
,其BaseAddress
属性设置为"https://api.somewhere.com"“。
但是,它总是获得一个带有空BaseUri的BaseUri,因此Handler不能在任何操作中使用HttpClient。
有人能看到出什么问题了吗?
发布于 2022-08-08 08:14:32
MediatR似乎注册了接口-实现对,因此您需要遵循相同的模式来进行类型化的客户端注册。尝试以下几点:
services.AddHttpClient<IRequestHandler<DummyRequest, string>, DummyHandler>((client) => { client.BaseAddress = new Uri("https://api.somewhere.com"); });
具有完整测试代码的要旨。
发布于 2022-08-08 10:29:52
您可以使用httpclient来代替类型化的httpclient。
因此注册为
builder.Services.AddHttpClient("somename", client => { client.BaseAddress = new Uri("https://api.somewhere.com"); });
在构造函数中,注入httpclientfactory,而不是:
public DummyHandler(HttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient("somename");
}
发布于 2022-08-08 10:24:06
我建议您围绕您的Http客户端创建包装类,并注册它,instead.It隐藏连接类型的instead.It,如果需要,可以通过其他逻辑或其他实现进行扩展。
示例:
class ApiConnection : IConnection
{
private readonly HttpClient _client;
public ApiConnection(...)
{
_client = new HttpClient();
}
// some other logic
}
将该类添加到您的handler (IConnection连接)中,并在处理程序中使用它。
Register as: services.AddSingleton<IConnection, APIConnection>();
https://stackoverflow.com/questions/73276826
复制相似问题