From 095cb605550c32cac000f6f7fe6fe8149eeaaaa1 Mon Sep 17 00:00:00 2001 From: Mattias Karlsson Date: Fri, 21 Nov 2025 08:03:56 +0100 Subject: [PATCH] Refactor Routes initialization for thread-safety and performance - Replace Dictionary with ConcurrentDictionary for EnableRoute and Routes - Combine two separate aggregations into single-pass processing - Use tuple structure (EnableRoute, Routes) to group related data during aggregation - Replace dictionary indexer assignments with TryAdd method calls - Update references from enableRoute to seed.EnableRoute within aggregation - Convert aggregation lambdas to static for performance optimization - Add System.Collections.Concurrent using statement --- src/Devlead.Testing.MockHttp/Routes.cs | 68 +++++++++++++------------- 1 file changed, 35 insertions(+), 33 deletions(-) diff --git a/src/Devlead.Testing.MockHttp/Routes.cs b/src/Devlead.Testing.MockHttp/Routes.cs index 4cd03a4..6c0f54a 100644 --- a/src/Devlead.Testing.MockHttp/Routes.cs +++ b/src/Devlead.Testing.MockHttp/Routes.cs @@ -3,6 +3,7 @@ using System.Net; using System.Text.Json.Serialization; using Microsoft.Extensions.DependencyInjection; +using System.Collections.Concurrent; namespace Devlead.Testing.MockHttp; @@ -77,40 +78,41 @@ static ImmutableArray GetRoutes() return _routes ??= ImmutableArray.Create(System.Text.Json.JsonSerializer.Deserialize(Resources.GetString("Routes.json") ?? throw new ArgumentNullException("routesJson")) ?? throw new ArgumentNullException("routes")); } } - var routes = GetRoutes(); - - - var enableRoute = routes - .Aggregate( - new Dictionary<( - HttpMethod Method, - string AbsoluteUri - ), - Action - >(), - (seed, value) => - { - void Enable(bool enabled) => value.Request.Disabled = !enabled; - foreach (var method in value.Request.Methods) - { - seed[(method, value.Request.AbsoluteUri)] = Enable; - } - return seed; - }, - seed => seed.ToImmutableDictionary() - ); + var routes = GetRoutes(); var result = routes .Aggregate( - new Dictionary<( - HttpMethod Method, - string AbsoluteUri - ), - Func - >(), - (seed, value) => + ( + EnableRoute: routes + .Aggregate( + new ConcurrentDictionary<( + HttpMethod Method, + string AbsoluteUri + ), + Action + >(), + static (seed, value) => + { + void Enable(bool enabled) => value.Request.Disabled = !enabled; + foreach (var method in value.Request.Methods) + { + seed.TryAdd((method, value.Request.AbsoluteUri), Enable); + } + + return seed; + }, + seed => seed.ToImmutableDictionary() + ), + Routes: new ConcurrentDictionary<( + HttpMethod Method, + string AbsoluteUri + ), + Func + >() + ), + static (seed, value) => { static HttpResponseMessage AddHeaders(HttpResponseMessage response, Dictionary headers) { @@ -184,7 +186,7 @@ static HttpResponseMessage AddHeaders(HttpResponseMessage response, Dictionary seed.ToImmutableDictionary() + static seed => seed.Routes.ToImmutableDictionary() ); return result;