refactor: optimized & added reload method for type factory
This commit is contained in:
parent
29f6c83bf0
commit
cddb30c631
@ -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<string, Type> registeredTypes = [];
|
||||
|
||||
public static string GetTypeName(Type type) => type.FullName ?? throw new ArgumentException($"{type.Name} must be a resolvable type");
|
||||
|
||||
public static T Get<T>(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<Type> 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);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user