我正在尝试理解依赖注入和仓储模式之间的区别。
根据我的理解,除了在依赖注入中使用构造函数注入之外,仓储模式可以完成所有依赖注入所做的事情。
好的,让我试着给出一个例子来解释:(请注意,我在使用Unity框架进行依赖注入)
创建Product类
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;
}
}
在Bootstrap.cs中初始化依赖项注入(DI)
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
}
我的问题
- 仓储模式和DI之间有什么区别?
- 构造函数注入的优点是什么?
- 如果有人能尽可能详细地解释Bootstrap.cs文件代码和Controller类代码,我将不胜感激。