From 29949fa64f486f3a0b3ce268d2da5175f999e0f9 Mon Sep 17 00:00:00 2001 From: Valters Melnalksnis Date: Fri, 24 Jun 2022 16:28:12 +0300 Subject: [PATCH] fix: Cache user agent header value Currently the user agent header value was created for each TokenDelegatingHandler and NordigenHttpClient. By creating the header value once, both the execution time and allocated memory for GetRequiredService() was reduced. Original: | Mean | Error | StdDev | Gen 0 | Gen 1 | Allocated | |--------- |---------:|---------:|-------:|-------:|----------:| | 33.16 us | 0.102 us | 0.090 us | 5.3101 | 0.0916 | 44 KB | After caching: | Mean | Error | StdDev | Gen 0 | Gen 1 | Allocated | |--------- |---------:|---------:|-------:|-------:|----------:| | 26.02 us | 0.091 us | 0.086 us | 4.8218 | 0.0000 | 39 KB | --- .../ServiceCollectionExtensions.cs | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/source/VMelnalksnis.NordigenDotNet.DependencyInjection/ServiceCollectionExtensions.cs b/source/VMelnalksnis.NordigenDotNet.DependencyInjection/ServiceCollectionExtensions.cs index 2f674d7..ef013ab 100644 --- a/source/VMelnalksnis.NordigenDotNet.DependencyInjection/ServiceCollectionExtensions.cs +++ b/source/VMelnalksnis.NordigenDotNet.DependencyInjection/ServiceCollectionExtensions.cs @@ -4,7 +4,9 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net.Http; +using System.Net.Http.Headers; using JetBrains.Annotations; @@ -27,6 +29,15 @@ namespace VMelnalksnis.NordigenDotNet.DependencyInjection; [PublicAPI] public static class ServiceCollectionExtensions { + private static readonly ProductInfoHeaderValue _userAgent; + + static ServiceCollectionExtensions() + { + var assemblyName = typeof(INordigenClient).Assembly.GetName(); + var assemblyShortName = assemblyName.Name ?? assemblyName.FullName.Split(',').First(); + _userAgent = new(assemblyShortName, assemblyName.Version?.ToString()); + } + /// Adds all required services for . /// The service collection in which to register the services. /// The configuration to which to bind options models. @@ -75,15 +86,6 @@ public static class ServiceCollectionExtensions private static void ConfigureNordigenClient(IServiceProvider provider, HttpClient client) { client.BaseAddress = provider.GetRequiredService>().CurrentValue.BaseAddress; - - var assembly = typeof(INordigenClient).Assembly.GetName(); - - var assemblyName = assembly.Name ?? - throw new InvalidOperationException($"Assembly {assembly.FullName} name is not specified"); - - var assemblyVersion = assembly.Version ?? - throw new InvalidOperationException($"Assembly {assembly.FullName} version is not specified"); - - client.DefaultRequestHeaders.UserAgent.Add(new(assemblyName, assemblyVersion.ToString())); + client.DefaultRequestHeaders.UserAgent.Add(_userAgent); } }