73 lines
1.5 KiB
C#
73 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using Svrnty.CQRS.Events.Abstractions.Sagas;
|
|
|
|
namespace Svrnty.CQRS.Events.Sagas;
|
|
|
|
/// <summary>
|
|
/// In-memory implementation of saga data storage.
|
|
/// </summary>
|
|
public sealed class SagaData : ISagaData
|
|
{
|
|
private readonly Dictionary<string, object> _data = new();
|
|
|
|
/// <inheritdoc />
|
|
public T? Get<T>(string key)
|
|
{
|
|
if (_data.TryGetValue(key, out var value))
|
|
{
|
|
if (value is T typedValue)
|
|
return typedValue;
|
|
|
|
// Attempt conversion
|
|
try
|
|
{
|
|
return (T)Convert.ChangeType(value, typeof(T));
|
|
}
|
|
catch
|
|
{
|
|
return default;
|
|
}
|
|
}
|
|
|
|
return default;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public void Set<T>(string key, T value)
|
|
{
|
|
if (value == null)
|
|
{
|
|
_data.Remove(key);
|
|
}
|
|
else
|
|
{
|
|
_data[key] = value;
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public bool Contains(string key)
|
|
{
|
|
return _data.ContainsKey(key);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public IDictionary<string, object> GetAll()
|
|
{
|
|
return new Dictionary<string, object>(_data);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load data from dictionary.
|
|
/// </summary>
|
|
public void LoadFrom(IDictionary<string, object> data)
|
|
{
|
|
_data.Clear();
|
|
foreach (var kvp in data)
|
|
{
|
|
_data[kvp.Key] = kvp.Value;
|
|
}
|
|
}
|
|
}
|