TourIAm/TIAMWebApp/Server/Services/DynamicMethodCallModel.cs

35 lines
1.3 KiB
C#

using System.Collections.Concurrent;
using System.Reflection;
using AyCode.Services.SignalRs;
namespace TIAMWebApp.Server.Services;
public class DynamicMethodCallModel<TAttribute> where TAttribute : TagAttribute
{
public object InstanceObject { get; init; }
public ConcurrentDictionary<int, MethodInfoModel<TAttribute>> MethodsByMessageTag { get; init; } = new();
public DynamicMethodCallModel(Type instanceObjectType) : this(instanceObjectType, null!)
{
}
public DynamicMethodCallModel(Type instanceObjectType, params object[] constructorParams) : this(Activator.CreateInstance(instanceObjectType, constructorParams)!)
{
}
public DynamicMethodCallModel(object instanceObject)
{
InstanceObject = instanceObject;
foreach (var methodInfo in instanceObject.GetType().GetMethods())
{
if (methodInfo.GetCustomAttribute(typeof(TAttribute)) is not TAttribute attribute) continue;
if (MethodsByMessageTag.ContainsKey(attribute.MessageTag))
throw new Exception($"Multiple SignaRMessageTag! messageTag: {attribute.MessageTag}; methodName: {methodInfo.Name}");
MethodsByMessageTag[attribute.MessageTag] = new MethodInfoModel<TAttribute>(attribute, methodInfo!);
}
}
}