2
0

ScannerServiceCollectionExtensions.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using FastGithub.Scanner;
  2. using Microsoft.Extensions.Configuration;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using System;
  5. using System.Net.Http;
  6. using System.Net.Http.Headers;
  7. using System.Net.Security;
  8. using System.Net.Sockets;
  9. namespace FastGithub
  10. {
  11. /// <summary>
  12. /// 服务注册扩展
  13. /// </summary>
  14. public static class ScannerServiceCollectionExtensions
  15. {
  16. /// <summary>
  17. /// 注册程序集下所有服务下选项
  18. /// </summary>
  19. /// <param name="services"></param>
  20. /// <param name="configuration">配置</param>
  21. /// <returns></returns>
  22. public static IServiceCollection AddGithubScanner(this IServiceCollection services, IConfiguration configuration)
  23. {
  24. var assembly = typeof(ScannerServiceCollectionExtensions).Assembly;
  25. var defaultUserAgent = new ProductInfoHeaderValue(assembly.GetName().Name ?? nameof(FastGithub), assembly.GetName().Version?.ToString());
  26. services
  27. .AddHttpClient(nameof(FastGithub))
  28. .SetHandlerLifetime(TimeSpan.FromMinutes(5d))
  29. .ConfigureHttpClient(httpClient =>
  30. {
  31. httpClient.Timeout = TimeSpan.FromSeconds(10d);
  32. httpClient.DefaultRequestHeaders.Accept.TryParseAdd("*/*");
  33. httpClient.DefaultRequestHeaders.UserAgent.Add(defaultUserAgent);
  34. })
  35. .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
  36. {
  37. Proxy = null,
  38. UseProxy = false,
  39. AllowAutoRedirect = false,
  40. ConnectCallback = async (ctx, ct) =>
  41. {
  42. var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  43. await socket.ConnectAsync(ctx.DnsEndPoint, ct);
  44. var stream = new NetworkStream(socket, ownsSocket: true);
  45. if (ctx.InitialRequestMessage.Headers.Host == null)
  46. {
  47. return stream;
  48. }
  49. var sslStream = new SslStream(stream, leaveInnerStreamOpen: false, delegate { return true; });
  50. await sslStream.AuthenticateAsClientAsync(string.Empty, null, false);
  51. return sslStream;
  52. }
  53. })
  54. .AddHttpMessageHandler<GithubDnsHttpHandler>();
  55. return services
  56. .AddMemoryCache()
  57. .AddServiceAndOptions(assembly, configuration)
  58. .AddHostedService<GithubFullScanHostedService>()
  59. .AddHostedService<GithubResultScanHostedService>()
  60. .AddSingleton<IGithubScanResults>(appService => appService.GetRequiredService<GithubScanResults>());
  61. ;
  62. }
  63. }
  64. }