50 lines
1.5 KiB
C#
50 lines
1.5 KiB
C#
using JetBrains.Annotations;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Reflection;
|
|
|
|
namespace NEG.Utils
|
|
{
|
|
public class KeyBasedFactory<T1, T2>
|
|
{
|
|
[PublicAPI] protected Dictionary<T1, Type> data;
|
|
|
|
public KeyBasedFactory()
|
|
{
|
|
data = new Dictionary<T1, Type>();
|
|
}
|
|
|
|
public void FireRegistration()
|
|
{
|
|
ScanAssembly(typeof(T2).Assembly);
|
|
|
|
if (typeof(T2).Assembly.GetType().Assembly == typeof(T2).Assembly)
|
|
return;
|
|
|
|
ScanAssembly(typeof(T2).Assembly.GetType().Assembly);
|
|
}
|
|
|
|
private static void ScanAssembly(Assembly assembly)
|
|
{
|
|
foreach (var type in assembly.GetTypes())
|
|
{
|
|
var methodFields =
|
|
type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
|
|
for (int i = 0; i < methodFields.Length; i++)
|
|
{
|
|
if (Attribute.GetCustomAttribute(methodFields[i], typeof(FactoryRegistration)) != null)
|
|
methodFields[i].Invoke(null, Array.Empty<object>());
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Register(T1 key, Type type) => data.Add(key, type);
|
|
|
|
public T2 CreateInstance(T1 key, params object[] args) => (T2)Activator.CreateInstance(data[key], args);
|
|
}
|
|
|
|
[AttributeUsage(AttributeTargets.Method)]
|
|
public class FactoryRegistration : Attribute
|
|
{
|
|
}
|
|
} |