Guest User

Untitled

a guest
Jan 19th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections.Concurrent;
  6.  
  7. namespace VideoStore.Infrastructure
  8. {
  9. public abstract class InMemoryRepository<T> : ICommands<T>, IQueries<T> where T : IEntity
  10. {
  11. protected static ConcurrentDictionary<int, T> items;
  12.  
  13. public IQueryable<T> All()
  14. {
  15. return items.Values.AsQueryable();
  16. }
  17.  
  18. public T ById(int id)
  19. {
  20. if (items.ContainsKey(id))
  21. return items[id];
  22. return default(T);
  23. }
  24.  
  25. private object lockObj = new Object();
  26. public T Add(T entity)
  27. {
  28. lock (lockObj)
  29. {
  30. var newId = items.Keys.Max() + 1;
  31. entity.Id = newId;
  32. items.TryAdd(newId, entity);
  33. }
  34. return entity;
  35. }
  36.  
  37. public T Update(T entity)
  38. {
  39. items[entity.Id] = entity;
  40. return entity;
  41. }
  42.  
  43. public void Remove(int id)
  44. {
  45. T x;
  46. items.TryRemove(id, out x);
  47. }
  48. }
  49. }
Add Comment
Please, Sign In to add comment