using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Unosquare.Swan.Components {
///
/// A thread-safe collection cache repository for types.
///
/// The type of member to cache.
public class CollectionCacheRepository {
private readonly Lazy>> _data =
new Lazy>>(() =>
new ConcurrentDictionary>(), true);
///
/// Determines whether the cache contains the specified key.
///
/// The key.
/// true if the cache contains the key, otherwise false.
public Boolean ContainsKey(Type key) => this._data.Value.ContainsKey(key);
///
/// Retrieves the properties stored for the specified type.
/// If the properties are not available, it calls the factory method to retrieve them
/// and returns them as an array of PropertyInfo.
///
/// The key.
/// The factory.
///
/// An array of the properties stored for the specified type.
///
/// type.
public IEnumerable Retrieve(Type key, Func> factory) {
if(factory == null) {
throw new ArgumentNullException(nameof(factory));
}
return this._data.Value.GetOrAdd(key, k => factory.Invoke(k).Where(item => item != null));
}
}
}