AzureCosmosFactory.cs 2.1 KB

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