Supercell.GUT/Supercell.GUT.Logic/Message/GUTMessageFactory.cs

41 lines
1.3 KiB
C#
Raw Normal View History

using Supercell.GUT.Logic.Message.Attributes;
using Supercell.GUT.Titan.Logic.Message;
using System.Collections.Immutable;
using System.Reflection;
namespace Supercell.GUT.Logic.Message;
public class GUTMessageFactory : LogicMessageFactory
{
private readonly ImmutableDictionary<int, Type> s_types;
public GUTMessageFactory() : base()
{
this.s_types = CreateMessageMap();
}
public override PiranhaMessage? CreateMessageByType(int messageType)
{
return this.s_types.TryGetValue(messageType, out Type? type) ?
Activator.CreateInstance(type) as PiranhaMessage : null;
}
private static ImmutableDictionary<int, Type> CreateMessageMap()
{
var builder = ImmutableDictionary.CreateBuilder<int, Type>();
IEnumerable<Type> types = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.GetCustomAttribute<VersionedMessageAttribute>() != null);
foreach (var type in types)
{
VersionedMessageAttribute attribute = type.GetCustomAttribute<VersionedMessageAttribute>()!;
if (!builder.TryAdd(attribute.MessageType, type))
throw new Exception($"Piranha message with type {attribute.MessageType} defined twice!");
}
return builder.ToImmutable();
}
}