使用 ASP.NET 核心内置 IoC 容器注入多个客户端而不是一个

Injecting multiple clients instead of just one using ASP.NET Core built-in IoC container

如何使用多个 API/Secret 密钥对多个客户端进行 DI?我当前的实现只能使用相同的 API/Secret 键注入一个 BinanceClientBinanceSocketClient

是否可以通过内置的 IServiceProvider 实现?类似于:

private readonly IEnumerable<IBinanceClient> _client;
private readonly IEnumerable<IBinanceSocketClient> _socketClient;

片段

var exchangeOptions = Configuration.GetSection(ExchangeOptions.Exchange).Get<ExchangeOptions>();

services.AddTransient<IBinanceClient, BinanceClient>(_ =>
    new BinanceClient(new BinanceClientOptions
    {
        ApiCredentials = new ApiCredentials(exchangeOptions.ApiKey, exchangeOptions.SecretKey),
        AutoTimestamp = true,
        AutoTimestampRecalculationInterval = TimeSpan.FromMinutes(30),
        TradeRulesBehaviour = TradeRulesBehaviour.AutoComply
    }));
services.AddSingleton<IBinanceSocketClient, BinanceSocketClient>(_ =>
    new BinanceSocketClient(new BinanceSocketClientOptions
    {
        ApiCredentials = new ApiCredentials(exchangeOptions.ApiKey, exchangeOptions.SecretKey),
        AutoReconnect = true,
        ReconnectInterval = TimeSpan.FromSeconds(15)
    }));
[ApiController]
[Route("api/[controller]")]
public class AlertsController : ControllerBase
{
    private readonly ILogger<AlertsController> _logger;
    private readonly IBinanceClient _client;
    private readonly IBinanceSocketClient _socketClient;
    private readonly IAlertService _alertService;

    public AlertsController(ILogger<AlertsController> logger, IBinanceClient client, IBinanceSocketClient socketClient, IAlertService alertService)
    {
        _logger = logger;
        _client = client;
        _socketClient = socketClient;
        _alertService = alertService;
    }

    ...
}

您可以像这样在 DI 设置中注入服务的多个版本:

services.AddTransient<IBinanceClient, BinanceClient>(/* ... config version 1 ... */);
services.AddTransient<IBinanceClient, BinanceClient>(/* ... config version 2 ... */);
services.AddTransient<IBinanceClient, BinanceClient>(/* ... config version 3 ... */);

现在在你的消费中 class,如果你有这个:

public class AlertsController : ControllerBase
{
    private readonly IBinanceClient _client;

    public AlertsController(IBinanceClient client)
    {
        _client = client;
    }
}

然后 IBinanceClient 对象将包含最近添加的服务,在本例中为第三个版本。但是,您的消费服务可以像这样获取所有注入的对象:

public class AlertsController : ControllerBase
{
    private readonly IEnumerable<IBinanceClient> _clients;

    public AlertsController(IEnumerable<IBinanceClient> clients)
    {
        _clients = clients;
    }
}

现在您的消费者将有权访问所有 3 个 IBinanceClient 对象。