using System.Data; using System.Data.SqlClient; public class DatabaseDataStore : IDataStore { private readonly IDbConnection _connection; public DatabaseDataStore(string connectionString) { _connection = new SqlConnection(connectionString); _connection.Open(); } public void Add(string key, object value) { using (var command = _connection.CreateCommand()) { command.CommandText = "INSERT INTO DataStore (Key, Value) VALUES (@Key, @Value)"; command.Parameters.Add("Key", SqlDbType.NVarChar).Value = key; command.Parameters.Add("Value", SqlDbType.NVarChar).Value = JsonConvert.SerializeObject(value); command.ExecuteNonQuery(); } } public T Get(string key) { using (var command = _connection.CreateCommand()) { command.CommandText = "SELECT Value FROM DataStore WHERE Key = @Key"; command.Parameters.Add("Key", SqlDbType.NVarChar).Value = key; var value = command.ExecuteScalar() as string; return JsonConvert.DeserializeObject (value); } } public void Dispose() { _connection.Dispose(); } }
public class FileDataStore : IDataStore { private readonly string _filePath; private readonly IDictionaryThis example shows how to use a file as a data store. The `Add` method adds a key/value pair to a dictionary and saves it to a JSON file. The `Get` method retrieves a value from the dictionary based on the key. Package library: Newtonsoft.Json_data; public FileDataStore(string filePath) { _filePath = filePath; if (File.Exists(_filePath)) { var json = File.ReadAllText(_filePath); _data = JsonConvert.DeserializeObject >(json); } else { _data = new Dictionary (); } } public void Add(string key, object value) { _data[key] = value; Save(); } public T Get (string key) { if (_data.TryGetValue(key, out var value)) { return (T)value; } return default(T); } private void Save() { var json = JsonConvert.SerializeObject(_data, Formatting.Indented); File.WriteAllText(_filePath, json); } public void Dispose() { Save(); } }