AzureCosmosFactory.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using Azure.Cosmos;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using Microsoft.Extensions.Logging;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. namespace TEAMModelOS.SDK.DI
  10. {
  11. public class AzureCosmosFactory
  12. {
  13. private readonly IServiceProvider _services;
  14. private readonly IOptionsMonitor<AzureCosmosFactoryOptions> _optionsMonitor;
  15. //private Option _option;
  16. private ConcurrentDictionary<string, CosmosClient> CosmosClients { get; } = new ConcurrentDictionary<string, CosmosClient>();
  17. // private CosmosDatabase database { get; set; }
  18. public AzureCosmosFactory(IServiceProvider services, IOptionsMonitor<AzureCosmosFactoryOptions> optionsMonitor)
  19. {
  20. if (services == null) throw new ArgumentNullException(nameof(services));
  21. if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
  22. _optionsMonitor = optionsMonitor;
  23. _services = services;
  24. }
  25. /// <summary>
  26. /// 取得CosmosClient,支持安全執行緒
  27. /// </summary>
  28. /// <param name="name"></param>
  29. /// <param name="region">可以使用Regions.{區域}設置,指定此屬性後,SDK會首選該區域來執行操作。此外,SDK會自動選擇後備的地理複製區域以實現高可用性。如果未指定此屬性,則SDK會將寫區域用作所有操作的首選區域</param>
  30. /// <returns></returns>
  31. public CosmosClient GetCosmosClient(string region = null, string name = "Default")
  32. {
  33. try
  34. {
  35. //CosmosClientOptions 的 SerializerOptions = new CosmosSerializationOptions() { PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase }
  36. //需等待官方修正
  37. var cm = CosmosClients.GetOrAdd(name, x => new CosmosClient(_optionsMonitor.Get(name).CosmosConnectionString, new CosmosClientOptions() { ApplicationRegion = region }));
  38. return cm; ;
  39. }
  40. catch (Exception e)
  41. {
  42. throw new Exception($"GetCosmosClient error:{e.Message}{e.StackTrace}");
  43. }
  44. }
  45. }
  46. }