firebase / firebase-admin-dotnet

Firebase Admin .NET SDK
https://firebase.google.com/docs/admin/setup
Apache License 2.0
357 stars 129 forks source link

Question: HttpClientFactory custom http message handlers #360

Open Naxaliav opened 10 months ago

Naxaliav commented 10 months ago

Hello, do you have an example, how we can extend http client factory to add multiple http message handlers and keep current implementation of google http client factory? In essence, I have multiple handlers covering cross cutting concerns (traces, metrics, logs) which I am using with other typed http clients, I would like them to be reused. Ideally it would the best to resolve them from DI.

I have found similar issue in other library which uses google http client factory ref: https://github.com/googleapis/google-api-dotnet-client/issues/1756, however some of the implementation is missing in current.

For now I have implemented as such (since I could not find any other possible way)

// configure handlers, so I could resolve through IHttpMessageHandlerFactory
builder.Services.AddHttpClient("Firebase")
    .ConfigurePrimaryHttpMessageHandler(_ => // some proxy configuration)
    .AddHttpMessageHandler<CorrelationIdHandler>()
    .AddHttpMessageHandler<LoggingHandler>()
    .AddHttpMessageHandler<TracingHandler>();
// override google http client factory
public class FirebaseHttpClientFactory : HttpClientFactory
{
      private readonly IHttpMessageHandlerFactory _httpMessageHandlerFactory;

      public FirebaseHttpClientFactory(IHttpMessageHandlerFactory httpMessageHandlerFactory)
      {
             _httpMessageHandlerFactory = httpMessageHandlerFactory
      }

      protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
      {
             return _httpMessageHandlerFactory.CreateHandler("Firebase");
      }
}
// register firebase messaging 
builder.Services.AddSingleton(sp =>  return FirebaseMessaging.GetMessaging(FirebaseApp.Create(new AppOptions{
     Credential = // load from file
     HttpClientFactory = new FirebaseHttpClientFactory(sp.GetRequiredService<IHttpMessageHandlerFactory>())
}));

By doing this, it kinda works, however I loose a lot of functionality from SDK itself, like gzip, user agent name setter and other initializers.

Can you please confirm that this is the only way currently how to achieve this and whether this will work?

I can see that other google library ref: https://github.com/googleapis/google-api-dotnet-client/issues/1756 already decoupled itself from accepting implementation of google.HttpClientFactory to interface (what let's to use DI and pass multiple handlers).

Are you planning to make similar update to this library? If yes and you need help, please let me know :)

google-oss-bot commented 10 months ago

I found a few problems with this issue: