// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using MessagePack.Formatters; using MessagePack.Internal; namespace MessagePack.Resolvers { /// /// A base class for classes that want to cache their responses for perf reasons. /// internal abstract class CachingFormatterResolver : IFormatterResolver { /// /// The cache of types to their formatters. /// private readonly ThreadsafeTypeKeyHashTable formatters = new ThreadsafeTypeKeyHashTable(); /// public IMessagePackFormatter GetFormatter() { if (!this.formatters.TryGetValue(typeof(T), out IMessagePackFormatter formatter)) { formatter = this.GetFormatterCore(); this.formatters.TryAdd(typeof(T), formatter); } return (IMessagePackFormatter)formatter; } /// /// Looks up a formatter for a type that has not been previously cached. /// /// The type to be formatted. /// The formatter to use, or null if none found. protected abstract IMessagePackFormatter GetFormatterCore(); } }