Created
July 17, 2019 18:41
-
-
Save hesenger/7eea8d2be41791636f2dfe969c62614b to your computer and use it in GitHub Desktop.
AutoPersist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AutoPersist<T> : IEnumerable<T> | |
{ | |
private readonly object _lock = new object(); | |
private readonly List<T> _list; | |
private readonly string _path; | |
public AutoPersist() | |
{ | |
_path = FormatPath(); | |
if (File.Exists(_path)) | |
{ | |
var content = File.ReadAllText(_path); | |
_list = JsonConvert.DeserializeObject<List<T>>(content); | |
} | |
else | |
{ | |
_list = new List<T>(); | |
} | |
} | |
public int Count => _list.Count; | |
public virtual void Add(T obj) | |
{ | |
_list.Add(obj); | |
Persist(); | |
} | |
public virtual void Remove(T obj) | |
{ | |
_list.Remove(obj); | |
Persist(); | |
} | |
protected virtual void Persist() | |
{ | |
lock (_lock) | |
{ | |
File.WriteAllText(_path, JsonConvert.SerializeObject(_list)); | |
} | |
} | |
protected virtual string FormatPath() | |
{ | |
var path = HttpContext.Current == null | |
? "persist" | |
: HttpContext.Current.Server.MapPath("~/persist"); | |
Directory.CreateDirectory(path); | |
return Path.Combine(path, typeof(T).Name + ".json"); | |
} | |
public virtual IEnumerator<T> GetEnumerator() | |
{ | |
return _list.GetEnumerator(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return _list.GetEnumerator(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment