Guest User

Untitled

a guest
Jul 26th, 2018
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. am i using dependency incection with unity the right way?
  2. public interface IUserRepository
  3. {
  4. List<User> getAll();
  5. }
  6.  
  7. public class UserRepository : IUserRepository
  8. {
  9.  
  10. private MyDbContext db;
  11.  
  12. public UserRepository(MyDbContext db)
  13. {
  14. this.db = db;
  15. }
  16.  
  17. public List<DomainModel.User> getAll()
  18. {
  19. return db.Users.ToList();
  20. }
  21. }
  22.  
  23. public class FakeUserRepository : IUserRepository
  24. {
  25. private List<User> userSet;
  26.  
  27. public FakeUserRepository()
  28. {
  29. // Fake Data
  30. userSet = new List<User>();
  31. userSet.Add(new User { Username = "john", Active = true, EMail = "john@ann.net", Password = "supersecret" });
  32. userSet.Add(new User { Username = "ashley", Active = true, EMail = "ashley@ann.net", Password = "supersecret" });
  33. userSet.Add(new User { Username = "kaidan", Active = true, EMail = "kaidan@ann.net", Password = "supersecret" });
  34. userSet.Add(new User { Username = "tali", Active = true, EMail = "tali@ann.net", Password = "supersecret" });
  35.  
  36. }
  37.  
  38. public List<DomainModel.User> getAll()
  39. {
  40. return userSet;
  41. }
  42.  
  43. }
  44.  
  45. // To Keep it simple, i skipped the IDisposable part ;)
  46.  
  47. public class UnitOfWork
  48. {
  49. MyDbContext db;
  50. private IUserRepository userRepository;
  51. UnityContainer container = new UnityContainer();
  52. public UnitOfWork(bool fake = false)
  53. {
  54. if (fake)
  55. {
  56. container.RegisterType<IUserRepository, FakeUserRepository>();
  57. }
  58. else
  59. {
  60. db = = new MyDbContext();
  61. container.RegisterType<IUserRepository, UserRepository>(new InjectionConstructor(db));
  62. }
  63. }
  64.  
  65.  
  66. public IUserRepository UserRepository
  67. {
  68. get
  69. {
  70. if (userRepository == null)
  71. {
  72. userRepository = container.Resolve<IUserRepository>();
  73. }
  74. return userRepository;
  75. }
  76. }
  77.  
  78. public void Save()
  79. {
  80. db.SaveChanges();
  81. }
  82. }
Add Comment
Please, Sign In to add comment