// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; // require UNITY_2018_3_OR_NEWER using System.Reflection; using MessagePack.Formatters; namespace MessagePack.Resolvers { /// /// Get formatter from . /// public sealed class AttributeFormatterResolver : IFormatterResolver { /// /// The singleton instance that can be used. /// public static readonly AttributeFormatterResolver Instance = new AttributeFormatterResolver(); private AttributeFormatterResolver() { } public IMessagePackFormatter GetFormatter() { return FormatterCache.Formatter; } private static class FormatterCache { public static readonly IMessagePackFormatter Formatter; static FormatterCache() { #if UNITY_2018_3_OR_NEWER && !NETFX_CORE var attr = (MessagePackFormatterAttribute)typeof(T).GetCustomAttributes(typeof(MessagePackFormatterAttribute), true).FirstOrDefault(); #else MessagePackFormatterAttribute attr = typeof(T).GetTypeInfo().GetCustomAttribute(); #endif if (attr == null) { return; } if (attr.Arguments == null) { Formatter = (IMessagePackFormatter)Activator.CreateInstance(attr.FormatterType); } else { Formatter = (IMessagePackFormatter)Activator.CreateInstance(attr.FormatterType, attr.Arguments); } } } } }