Skip to content

Commit b073715

Browse files
authored
Add thread-safe initialization for Routes with framework-specific locking (#183)
- Introduce _lock field with conditional compilation: - Use Lock type for .NET 9.0 and greater - Fallback to object for older framework versions - Refactor InitializeRoutesFromResource to use local static GetRoutes method - Wrap _routes initialization in lock to prevent race conditions
1 parent 554b953 commit b073715

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/Devlead.Testing.MockHttp/Routes.cs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,25 @@ string AbsoluteUri
6060
=> InitializeRoutesFromResource();
6161

6262

63+
private static readonly
64+
#if NET9_0_OR_GREATER
65+
Lock
66+
#else
67+
object
68+
#endif
69+
_lock = new ();
70+
6371
private static ImmutableDictionary<(HttpMethod Method, string PathAndQuery), Func<HttpRequestMessage, HttpResponseMessage>> InitializeRoutesFromResource()
6472
{
65-
var routesJson = Resources<T>.GetString("Routes.json");
66-
ArgumentException.ThrowIfNullOrEmpty(routesJson);
73+
static ImmutableArray<Route> GetRoutes()
74+
{
75+
lock (_lock)
76+
{
77+
return _routes ??= ImmutableArray.Create(System.Text.Json.JsonSerializer.Deserialize<Route[]>(Resources<T>.GetString("Routes.json") ?? throw new ArgumentNullException("routesJson")) ?? throw new ArgumentNullException("routes"));
78+
}
79+
}
80+
var routes = GetRoutes();
6781

68-
var routes = _routes ??= ImmutableArray.Create(System.Text.Json.JsonSerializer.Deserialize<Route[]>(routesJson) ?? throw new ArgumentNullException(nameof(routesJson)));
6982

7083
var enableRoute = routes
7184
.Aggregate(

0 commit comments

Comments
 (0)