diff --git a/dotnet/src/webdriver/BiDi/Json/Converters/BrowserUserContextConverter.cs b/dotnet/src/webdriver/BiDi/Json/Converters/BrowserUserContextConverter.cs index 47e1a2cc4ee1f..e1e939ba11196 100644 --- a/dotnet/src/webdriver/BiDi/Json/Converters/BrowserUserContextConverter.cs +++ b/dotnet/src/webdriver/BiDi/Json/Converters/BrowserUserContextConverter.cs @@ -17,6 +17,8 @@ // under the License. // +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; using System.Text.Json; using System.Text.Json.Serialization; using OpenQA.Selenium.BiDi.Browser; @@ -25,11 +27,15 @@ namespace OpenQA.Selenium.BiDi.Json.Converters; internal class BrowserUserContextConverter(IBiDi bidi) : JsonConverter { + private static readonly ConditionalWeakTable> s_cache = new(); + public override UserContext? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var id = reader.GetString(); - return new UserContext(id!) { BiDi = bidi }; + var sessionCache = s_cache.GetValue(bidi, _ => new ConcurrentDictionary()); + + return sessionCache.GetOrAdd(id!, key => new UserContext(bidi, key)); } public override void Write(Utf8JsonWriter writer, UserContext value, JsonSerializerOptions options) diff --git a/dotnet/src/webdriver/BiDi/Json/Converters/BrowsingContextConverter.cs b/dotnet/src/webdriver/BiDi/Json/Converters/BrowsingContextConverter.cs index e91923d49fa01..86d7c77c7f074 100644 --- a/dotnet/src/webdriver/BiDi/Json/Converters/BrowsingContextConverter.cs +++ b/dotnet/src/webdriver/BiDi/Json/Converters/BrowsingContextConverter.cs @@ -17,6 +17,8 @@ // under the License. // +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; using System.Text.Json; using System.Text.Json.Serialization; @@ -24,13 +26,15 @@ namespace OpenQA.Selenium.BiDi.Json.Converters; internal class BrowsingContextConverter(IBiDi bidi) : JsonConverter { - private readonly IBiDi _bidi = bidi; + private static readonly ConditionalWeakTable> s_cache = new(); public override BrowsingContext.BrowsingContext? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var id = reader.GetString(); - return new BrowsingContext.BrowsingContext(id!) { BiDi = _bidi }; + var sessionCache = s_cache.GetValue(bidi, _ => new ConcurrentDictionary()); + + return sessionCache.GetOrAdd(id!, key => new BrowsingContext.BrowsingContext(bidi, key)); } public override void Write(Utf8JsonWriter writer, BrowsingContext.BrowsingContext value, JsonSerializerOptions options)