diff --git a/src/Infrastructure/BotSharp.Abstraction/Utilities/ObjectExtensions.cs b/src/Infrastructure/BotSharp.Abstraction/Utilities/ObjectExtensions.cs new file mode 100644 index 000000000..7b3bca61b --- /dev/null +++ b/src/Infrastructure/BotSharp.Abstraction/Utilities/ObjectExtensions.cs @@ -0,0 +1,55 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using JsonSerializer = System.Text.Json.JsonSerializer; + +namespace BotSharp.Abstraction.Utilities +{ + public static class ObjectExtensions + { + private static readonly JsonSerializerOptions DefaultOptions = new() + { + ReferenceHandler = ReferenceHandler.IgnoreCycles + }; + private static JsonSerializerSettings DefaultSettings = new() + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }; + + public static T DeepClone(this T obj) where T : class + { + if (obj == null) return null; + + try + { + var json = JsonSerializer.Serialize(obj, DefaultOptions); + return JsonSerializer.Deserialize(json, DefaultOptions); + } + catch(Exception ex) + { + Console.WriteLine($"DeepClone Error:{ex}"); + return DeepCloneWithNewtonsoft(obj); + } + } + + private static T DeepCloneWithNewtonsoft(this T obj) where T : class + { + if (obj == null) return null; + + try + { + var json = JsonConvert.SerializeObject(obj, DefaultSettings); + return JsonConvert.DeserializeObject(json, DefaultSettings); + } + catch(Exception ex) + { + Console.WriteLine($"DeepClone Error:{ex}"); + return obj; + } + } + } +} diff --git a/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.LoadAgent.cs b/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.LoadAgent.cs index ef81adafd..2dcd15b77 100644 --- a/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.LoadAgent.cs +++ b/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.LoadAgent.cs @@ -14,7 +14,7 @@ public async Task LoadAgent(string id, bool loadUtility = true) HookEmitter.Emit(_services, hook => hook.OnAgentLoading(ref id), id); - var agent = await GetAgent(id); + var agent = (await GetAgent(id)).DeepClone(); if (agent == null) return null; agent.TemplateDict = [];