ChipDemo/Core/Features/FeatureContainer.cs

51 lines
1.4 KiB
C#

using System.Collections.Immutable;
using Demo.Models;
namespace Demo.Features;
public class FeatureContainer : IFeatureContainer
{
private readonly IDictionary<string, FeatureList> _payloads;
private static readonly Lazy<FeatureContainer> _lazy = new Lazy<FeatureContainer>(() => new FeatureContainer());
private FeatureContainer()
{
_payloads = new Dictionary<string, FeatureList>();
}
public static FeatureContainer Instance => _lazy.Value;
public IFeatureContainer RegisterFeature(string signId, Feature feature)
{
if (_payloads.TryGetValue(signId, out var features))
{
features.TryAdd(feature.Name, feature);
}
else
{
_payloads.TryAdd(signId, new FeatureList() { { feature.Name, feature } });
}
return this;
}
public IFeatureContainer RegisterWrapper(Func<IMetadata, FeatureList, IFeatureWrapper> wrapper)
{
_wrapper = wrapper;
return this;
}
private Func<IMetadata, FeatureList, IFeatureWrapper>? _wrapper;
public IFeatureWrapper BuildWrapper(IMetadata metadata)
{
if (_payloads.TryGetValue(metadata.SignId, out var features))
{
return _wrapper?.Invoke(metadata, features) ?? new FeatureWrapper(metadata, features);
}
return new FeatureWrapper(metadata, features);
}
}