AzureServiceBusFactory.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using Microsoft.Extensions.Options;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using Azure.Messaging.ServiceBus;
  6. namespace TEAMModelOS.SDK.DI
  7. {
  8. public class AzureServiceBusFactory
  9. {
  10. private readonly IServiceProvider _services;
  11. private readonly IOptionsMonitor<AzureServiceBusFactoryOptions> _optionsMonitor;
  12. private readonly ILogger _logger;
  13. private ConcurrentDictionary<string, ServiceBusClient> ServiceBusClients { get; } = new ConcurrentDictionary<string, ServiceBusClient>();
  14. public AzureServiceBusFactory(IServiceProvider services, IOptionsMonitor<AzureServiceBusFactoryOptions> optionsMonitor, ILogger<AzureServiceBusFactory> logger)
  15. {
  16. if (services == null) throw new ArgumentNullException(nameof(services));
  17. if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
  18. _services = services;
  19. _optionsMonitor = optionsMonitor;
  20. _logger = logger;
  21. }
  22. public ServiceBusClient GetServiceBusClient(string name = "Default")
  23. {
  24. try
  25. {
  26. var client = ServiceBusClients.GetOrAdd(name, x => new ServiceBusClient(_optionsMonitor.Get(name).ServiceBusConnectionString));
  27. return client;
  28. }
  29. catch (OptionsValidationException e)
  30. {
  31. _logger?.LogWarning(e, e.Message);
  32. return null;
  33. }
  34. }
  35. }
  36. }