12345678910111213141516171819202122232425262728293031323334353637383940 |
- using Microsoft.Extensions.Options;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Collections.Concurrent;
- using Azure.Messaging.ServiceBus;
- namespace TEAMModelOS.SDK.DI
- {
- public class AzureServiceBusFactory
- {
- private readonly IServiceProvider _services;
- private readonly IOptionsMonitor<AzureServiceBusFactoryOptions> _optionsMonitor;
- private readonly ILogger _logger;
- private ConcurrentDictionary<string, ServiceBusClient> ServiceBusClients { get; } = new ConcurrentDictionary<string, ServiceBusClient>();
- public AzureServiceBusFactory(IServiceProvider services, IOptionsMonitor<AzureServiceBusFactoryOptions> optionsMonitor, ILogger<AzureServiceBusFactory> logger)
- {
- if (services == null) throw new ArgumentNullException(nameof(services));
- if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
- _services = services;
- _optionsMonitor = optionsMonitor;
- _logger = logger;
- }
- public ServiceBusClient GetServiceBusClient(string name = "Default")
- {
- try
- {
- var client = ServiceBusClients.GetOrAdd(name, x => new ServiceBusClient(_optionsMonitor.Get(name).ServiceBusConnectionString));
- return client;
- }
- catch (OptionsValidationException e)
- {
- _logger?.LogWarning(e, e.Message);
- return null;
- }
- }
- }
- }
|