1 例子

namespace AspNetCore.DependencyInjection.Models{public class Product{public string Name { get; set; }public decimal Price { get; set; }}}
接下来,在Models文件夹下创建一个接口名字为IRepository,这个接口中包含了最基本的方法新增,读取和删除产品,接口的代码如下:
namespace AspNetCore.DependencyInjection.Models{public interface IRepository{IEnumerable<Product> Products { get; }Product this[string name] { get; }void AddProduct(Product product);void DeleteProduct(Product product);}}
namespace AspNetCore.DependencyInjection.Models{public class Repository : IRepository{private Dictionary<string, Product> products;public Repository(){products = new Dictionary<string, Product>();new List<Product> {new Product { Name = "Women Shoes", Price = 99M },new Product { Name = "Skirts", Price = 29.99M },new Product { Name = "Pants", Price = 40.5M }}.ForEach(p => AddProduct(p));}public IEnumerable<Product> Products => products.Values;public Product this[string name] => products[name];public void AddProduct(Product product) => products[product.Name] = product;public void DeleteProduct(Product product) => products.Remove(product.Name);}}
我们修改一下HomeController.cs文件将我们的产品显示在视图上,因此更新Index方法
namespace AspNetCore.DependencyInjection.Controllers{public class HomeController : Controller{public IActionResult Index(){return View(new Repository().Products);}}}
可以清楚的看到在Index方法中,创建一个Repository实例并且调用了Products属性(new Repository().Products), 这个属性返回字典中存储的所有产品,我们最后将这些数据返回到视图
HomeController以紧耦合方式依赖Repository类,我们使用依赖注入技术实现松耦合
@{ViewData["Title"] = "Home Page";}@model IEnumerable<Product><div class="row mb-3"><div class="col-sm"><table class="table table-bordered align-middle"><thead><tr><th>名称</th><th>价格</th></tr></thead><tbody>@foreach (var product in Model){<tr><td>@product.Name</td><td>@string.Format("{0:C2}",product.Price)</td></tr>}</tbody></table></div></div>
这个视图通过循环Model中的数据读取产品信息,显示所有的产品在表格中,运行应用程序我们将看到3个产品信息

2 使用DI来解决紧耦合
如果你看到控制器中代码你将发现紧耦合Repository.cs类,原因是我们直接创建了一个Repository对象使用下面代码:
return View(new Repository().Products);public IActionResult Index(){return View(new NewRepository().Products);}
首先我们创建一个松耦合的依赖在控制器中,这个我们将实现一个接口并且在控制器中使用这个接口,更新一下HomeController代码因此使用这个接口来创建依赖,代码如下:
namespace AspNetCore.DependencyInjection.Controllers{public class HomeController : Controller{private IRepository _repository;public HomeController(IRepository repository){_repository= repository;}public IActionResult Index(){return View(new Repository().Products);}}}
using AspNetCore.DependencyInjection.Models;var builder = WebApplication.CreateBuilder(args);builder.Services.AddTransient<IRepository, Repository>();// Add services to the container.builder.Services.AddControllersWithViews();var app = builder.Build();
builder.Services.AddTransient<IRepository, NewRepository>()4 依赖注入针对单个类型
如果你有一个简单的类没有实现任何接口,该类是一个简单类型,让我们了解如何在这个例子中使用DI,在Models文件夹中创建一个新的类叫ProductSum.cs并添加如下代码
namespace AspNetCore.DependencyInjection.Models{public class ProductSum{public IRepository Repository { get; set; }public ProductSum(IRepository repo){Repository = repo;}public decimal Total => Repository.Products.Sum(p => p.Price);}}
注意这个类没有实现任何接口,在构造函数中指定一个IRepository依赖,有一个Total的属性,返回Repository类所有产品的总和,这个类依赖IRepository接口通过ServiceProvider来解析,我们在之前已经做了配置
namespace AspNetCore.DependencyInjection.Controllers{public class HomeController : Controller{private IRepository _repository;private ProductSum _productSum;public HomeController(IRepository repository, ProductSum productSum){_repository = repository;_productSum = productSum;}public IActionResult Index(){return View(new Repository().Products);}}}
在Program类中添加下面代码:
using AspNetCore.DependencyInjection.Models;var builder = WebApplication.CreateBuilder(args);builder.Services.AddTransient<IRepository, Repository>();builder.Services.AddTransient<ProductSum>();// Add services to the container.builder.Services.AddControllersWithViews();var app = builder.Build();
