How do I DI multiple clients with multiple API/Secret keys? My current implementation is able to inject only one BinanceClient
and BinanceSocketClient
with same API/Secret key.
Is that possible through the built-in IServiceProvider? Something like:
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;
}
...
}
You can inject multiple versions of a service in your DI setup like this:
services.AddTransient<IBinanceClient, BinanceClient>(/* ... config version 1 ... */);
services.AddTransient<IBinanceClient, BinanceClient>(/* ... config version 2 ... */);
services.AddTransient<IBinanceClient, BinanceClient>(/* ... config version 3 ... */);
Now in your consuming class, if you had this:
public class AlertsController : ControllerBase
{
private readonly IBinanceClient _client;
public AlertsController(IBinanceClient client)
{
_client = client;
}
}
Then the IBinanceClient
object would contain the most recently added service, in this case, the third version. However, your consuming service can take all of the injected objects like this:
public class AlertsController : ControllerBase
{
private readonly IEnumerable<IBinanceClient> _clients;
public AlertsController(IEnumerable<IBinanceClient> clients)
{
_clients = clients;
}
}
Now your consumer will have access to all 3 IBinanceClient
objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.