Skip to content

Commit b5cfd7e

Browse files
committed
Store already cloned objects in a dictionary to avoid circular dependency during cloning
1 parent 6f3e634 commit b5cfd7e

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

src/Microsoft.OpenApi/Helpers/DictionaryCloneHelper.cs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,26 @@ internal class DictionaryCloneHelper
2121
internal static Dictionary<T, U> Clone<T, U>(IDictionary<T, U> dictionary)
2222
{
2323
if (dictionary is null) return null;
24+
2425
var clonedDictionary = new Dictionary<T, U>(dictionary.Keys.Count);
26+
var clonedObjects = new Dictionary<object, object>();
2527

26-
foreach (var kvp in dictionary)
28+
foreach (var keyValuePair in dictionary)
2729
{
28-
// Create instance of the specified type using the constructor matching the specified parameter types.
29-
clonedDictionary[kvp.Key] = (U)Activator.CreateInstance(kvp.Value.GetType(), kvp.Value);
30-
}
31-
30+
// If the object has already been cloned, use the cloned object instead of cloning it again
31+
if (clonedObjects.TryGetValue(keyValuePair.Value, out var clonedValue))
32+
{
33+
clonedDictionary[keyValuePair.Key] = (U)clonedValue;
34+
}
35+
else
36+
{
37+
// Create instance of the specified type using the constructor matching the specified parameter types.
38+
clonedDictionary[keyValuePair.Key] = (U)Activator.CreateInstance(keyValuePair.Value.GetType(), keyValuePair.Value);
39+
40+
// Add the cloned object to the dictionary of cloned objects
41+
clonedObjects.Add(keyValuePair.Value, clonedDictionary[keyValuePair.Key]);
42+
}
43+
}
3244

3345
return clonedDictionary;
3446
}

0 commit comments

Comments
 (0)