我正在尝试对具有2个接口和1个字符串的DelegatingHandler
使用依赖项注入。
public class MessageHandler : DelegatingHandler
{
private readonly ILogger<MessageHandler> _logger;
private readonly ISomeService _someService;
public string Name { get; set; }
public MessageHandler(ILogger<MessageHandler> logger, ISomeService someService)
{
_logger = logger;
_someService = someService;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
Console.WriteLine($"Doing some other logic with {Name}");
var response = await base.SendAsync(request, cancellationToken);
_someService.DoSomething(Name);
return response;
}
}
我正在通过DelegatingHandler
将此HttpClient
添加到IHttpClientFactory
services.AddHttpClient("github")
.ConfigureHttpClient(c => { c.BaseAddress = new Uri("https://www.github.com"); })
.AddHttpMessageHandler<MessageHandler>(); // I want Name property to be 'github'
但是我也想将MessageHandler
与多个HttpClient
不同的Name
一起使用
services.AddHttpClient("twitter")
.ConfigureHttpClient(c => { c.BaseAddress = new Uri("https://www.twitter.com"); })
.AddHttpMessageHandler<MessageHandler>(); // I want Name property to be 'twitter'
有没有办法做到这一点?
services.AddHttpClient("github")
.ConfigureHttpClient(c => { c.BaseAddress = new Uri("https://www.github.com"); })
.AddHttpMessageHandler(provider =>
{
var logger = provider.GetRequiredService<ILogger<MessageHandler>>();
var someService = provider.GetRequiredService<ISomeService>();
return new MessageHandler(logger, someService, "github");
});
答案 0 :(得分:0)
鉴于原始示例具有以下构造函数
public MessageHandler(ILogger<MessageHandler> logger, ISomeService someService)
{
_logger = logger;
_someService = someService;
}
您可以解析处理程序,然后设置属性
services.AddTransient<MessageHandler>();
services.AddHttpClient("github")
.ConfigureHttpClient(c => { c.BaseAddress = new Uri("https://www.github.com"); })
.AddHttpMessageHandler(provider => {
var handler = provider.GetRequiredService<MessageHandler>();
handler.Name = "github";
return handler;
});
无论哪种方式,您都需要手动解析处理程序才能设置该字符串属性。
答案 1 :(得分:0)
您是如此亲密!使用依赖注入获取处理程序,然后设置字段:
services.AddHttpClient("github")
.ConfigureHttpClient(c => { c.BaseAddress = new Uri("https://www.github.com"); })
.AddHttpMessageHandler(provider =>
{
var handler = provider.GetRequiredService<MessageHandler>();
handler.Name = "github";
return handler;
});
这使DI框架可以处理MessageHandler
的所有依赖关系,而您只需要指定所需的名称即可。