You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ServiceCollectionExtensions.cs 2.0 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using Microsoft.Extensions.DependencyInjection;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Net.Http;
  8. using System.Net;
  9. using Discord.Net.Rest;
  10. using Discord.Rest.Net;
  11. namespace Discord.Rest.Extensions
  12. {
  13. /// <summary>
  14. /// Here you will find all the extensions to be able to add a Discord Client to an IServiceCollection
  15. /// </summary>
  16. public static class ServiceCollectionExtensions
  17. {
  18. /// <summary>
  19. /// Adds the DiscordRestClient as a Scoped Service to be able to use through DI.
  20. /// </summary>
  21. /// <param name="services">This is the IServiceCollection where all the services are located.</param>
  22. /// <param name="useProxy">Set this to true to use proxies, default is false.</param>
  23. /// <returns></returns>
  24. public static IServiceCollection AddDiscordRestClient(this IServiceCollection services, bool useProxy = false)
  25. {
  26. services.AddHttpClient("HttpClientFactoryRestClientProvider")
  27. .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
  28. {
  29. AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
  30. UseCookies = false,
  31. UseProxy = useProxy,
  32. });
  33. //services.AddScoped<HttpClientFactoryRestClientProvider>(provider => new HttpClientFactoryRestClientProvider(provider.GetRequiredService<IHttpClientFactory>()));
  34. services.AddSingleton<DiscordRestClient>(provider =>
  35. {
  36. var config = new DiscordRestConfig
  37. {
  38. RestClientProvider = url => new HttpClientFactoryRestClient(url, provider.GetRequiredService<IHttpClientFactory>().CreateClient("HttpClientFactoryRestClientProvider"), useProxy)
  39. };
  40. return new DiscordRestClient(config);
  41. });
  42. return services;
  43. }
  44. }
  45. }