From cddb30c6311117ff334101e2d28f09d768dc4b82 Mon Sep 17 00:00:00 2001 From: Syntriax Date: Mon, 28 Apr 2025 22:26:33 +0300 Subject: [PATCH] refactor: optimized & added reload method for type factory --- Engine.Core/Factory/TypeFactory.cs | 35 ++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/Engine.Core/Factory/TypeFactory.cs b/Engine.Core/Factory/TypeFactory.cs index e7a653d..d84d5de 100644 --- a/Engine.Core/Factory/TypeFactory.cs +++ b/Engine.Core/Factory/TypeFactory.cs @@ -1,10 +1,15 @@ using System; +using System.Collections.Generic; using System.Linq; namespace Syntriax.Engine.Core.Factory; public static class TypeFactory { + private static readonly Dictionary registeredTypes = []; + + public static string GetTypeName(Type type) => type.FullName ?? throw new ArgumentException($"{type.Name} must be a resolvable type"); + public static T Get(params object?[]? args) where T : class => (T)Get(typeof(T), args); public static object Get(string fullName, params object?[]? args) => Get(GetType(fullName), args); public static object Get(Type type, params object?[]? args) @@ -23,9 +28,31 @@ public static class TypeFactory } public static Type GetType(string fullName) - => AppDomain.CurrentDomain + { + if (registeredTypes.TryGetValue(fullName, out Type? result)) + return result; + + ReloadTypes(); + + if (registeredTypes.TryGetValue(fullName, out Type? reloadedType)) + return reloadedType; + + throw new Exception($"Type {fullName} could not be found in the current domain."); + } + + public static void ReloadTypes() + { + registeredTypes.Clear(); + + IEnumerable domainTypes = AppDomain.CurrentDomain .GetAssemblies() - .SelectMany(a => a.GetTypes()) - .FirstOrDefault(t => t.FullName?.CompareTo(fullName) == 0) - ?? throw new Exception($"Type {fullName} could not be found in the current domain."); + .SelectMany(a => a.GetTypes()); + + // TODO: Replace this + // There are some system & compiler generated types with duplicated names, + // it is ugly it will cause headaches in the future because it will not + // throw an error if there's a type with an unintended duplicate name + foreach (Type type in domainTypes) + registeredTypes.TryAdd(GetTypeName(type), type); + } }