Я пытаюсь понять Разницу между инжекцией зависимостей и шаблоном репозитория.Разница между впрыском зависимостей и шаблоном репозитория
Согласно моему пониманию, шаблон репозитория делает все, что делает инъекция зависимостей, за исключением Injection Dependency, мы используем Injection конструктора.
Хорошо, позвольте мне попытаться объяснить давая пример: (Пожалуйста, обратите внимание, я использую Unity Framework для DI)
Создание класса продукта
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Создание интерфейса на модели
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
bool Update(Product item);
bool Delete(int id);
}
Внедрение интерфейса
//ProductRepository.cs
public class ProductRepository : IProductRepository
{
private List<Product> products = new List<Product>();
private int _nextId = 1;
public ProductRepository()
{
// Add products for the Demonstration
Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M });
Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M });
Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });
}
public IEnumerable GetAll()
{
// TO DO : Code to get the list of all the records in database
return products;
}
public Product Get(int id)
{
// TO DO : Code to find a record in database
return products.Find(p => p.Id == id);
}
public Product Add(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
// TO DO : Code to save record into database
item.Id = _nextId++;
products.Add(item);
return item;
}
public bool Update(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
// TO DO : Code to update record into database
int index = products.FindIndex(p => p.Id == item.Id);
if (index == -1)
{
return false;
}
products.RemoveAt(index);
products.Add(item);
return true;
}
public bool Delete(int id)
{
// TO DO : Code to remove the records from database
products.RemoveAll(p => p.Id == id);
return true;
}
}
Для DI Initialize Зависимость в Bootstrap.cs
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
container.RegisterType<IProductRepository, ProductRepository>();
// e.g. container.RegisterType<ITestService, TestService>();
RegisterTypes(container);
return container;
}
Контроллер
public class ProductController : Controller
{
readonly IProductRepository repository;
//inject dependency
public ProductController(IProductRepository repository)
{
this.repository = repository;
}
public ActionResult Index()
{
var data = repository.GetAll();
return View(data);
}
//Other Code
}
Мои вопросы
- Какова разница между Repository Pattern и DI
- Что такое преимущество Constructory инъекций
- Цените Если кто-то может объяснить Bootstrap.cs код файла и код класса контроллера с максимально возможными деталями.
'В чем разница между шаблоном репозитория и DI? Это сравнение яблок и апельсинов. – McGarnagle
@McGarnagle Спасибо. Мой пример в основном создает репозиторий, единственное, что здесь имеет значение, - это инсталляция конструктора (DI) для достижения IOC. Мой вопрос в том, что это выгодно? Цените свое понимание. – Lynnw
@McGarnagle Впрыскивание зависимостей дает объект своим переменным экземпляра. Если вы внимательно прочитаете IOC, вкратце, он просто просит добавить интерфейс для создания абстракции, это то, что также создает шаблон репозитория ... и это причина, по которой я задал вопрос об ошибке. Проблема в StackOverflow заключается в том, что люди очень жесткие, и это полностью мое восприятие, основанное на полученном мной комментарии. Когда вы не знаете ответа, что является причиной для комментариев? Просто чтобы получить дополнительные баллы, чтобы показать вам своего босса? – Lynnw