SnowflakeIDExtensions.cs 1.1 KB

12345678910111213141516171819202122232425262728
  1. using Microsoft.Extensions.DependencyInjection;
  2. using Microsoft.Extensions.DependencyInjection.Extensions;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. namespace TEAMModelOS.SDK.DI
  7. {
  8. public static class SnowflakeIDExtensions
  9. {
  10. /// <summary>
  11. /// 分散式ID產生器 (Snowflake算法,支援線程安全)
  12. /// </summary>
  13. /// <param name="datacenterId">數據中心ID (0~31)</param>
  14. /// <param name="workerId">工作機器ID (0~31)</param>
  15. public static IServiceCollection AddSnowflakeId(this IServiceCollection services, long datacenterId, long workerId)
  16. {
  17. if (services == null) throw new ArgumentNullException(nameof(services));
  18. if (datacenterId > 31 || datacenterId < 0) throw new Exception("datacenterId only 0-31");
  19. if (workerId > 31 || workerId < 0) throw new Exception("workerId only 0-31");
  20. services.TryAddSingleton<SnowflakeId>();
  21. services.Configure<SnowflakeIDOptions>(o => { o.DatacenterId = datacenterId; o.WorkerId = workerId; });
  22. return services;
  23. }
  24. }
  25. }