Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- am i using dependency incection with unity the right way?
- public interface IUserRepository
- {
- List<User> getAll();
- }
- public class UserRepository : IUserRepository
- {
- private MyDbContext db;
- public UserRepository(MyDbContext db)
- {
- this.db = db;
- }
- public List<DomainModel.User> getAll()
- {
- return db.Users.ToList();
- }
- }
- public class FakeUserRepository : IUserRepository
- {
- private List<User> userSet;
- public FakeUserRepository()
- {
- // Fake Data
- userSet = new List<User>();
- userSet.Add(new User { Username = "john", Active = true, EMail = "john@ann.net", Password = "supersecret" });
- userSet.Add(new User { Username = "ashley", Active = true, EMail = "ashley@ann.net", Password = "supersecret" });
- userSet.Add(new User { Username = "kaidan", Active = true, EMail = "kaidan@ann.net", Password = "supersecret" });
- userSet.Add(new User { Username = "tali", Active = true, EMail = "tali@ann.net", Password = "supersecret" });
- }
- public List<DomainModel.User> getAll()
- {
- return userSet;
- }
- }
- // To Keep it simple, i skipped the IDisposable part ;)
- public class UnitOfWork
- {
- MyDbContext db;
- private IUserRepository userRepository;
- UnityContainer container = new UnityContainer();
- public UnitOfWork(bool fake = false)
- {
- if (fake)
- {
- container.RegisterType<IUserRepository, FakeUserRepository>();
- }
- else
- {
- db = = new MyDbContext();
- container.RegisterType<IUserRepository, UserRepository>(new InjectionConstructor(db));
- }
- }
- public IUserRepository UserRepository
- {
- get
- {
- if (userRepository == null)
- {
- userRepository = container.Resolve<IUserRepository>();
- }
- return userRepository;
- }
- }
- public void Save()
- {
- db.SaveChanges();
- }
- }
Add Comment
Please, Sign In to add comment