具有多个构造函数参数和选项的DelegatingHandler的依赖项注入

时间:2019-05-07 23:44:25

标签: c# dependency-injection .net-core

我正在尝试对具有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");
    });

2 个答案:

答案 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的所有依赖关系,而您只需要指定所需的名称即可。