private ICustomerRepository _customerRepository;
public CustomerController()
{
_customerRepository = new EfCustomerRepository(
new CustomerContext(new DbContextOptions<CustomerContext>{}));
}
var repository = new Data.MemoryCustomerRepository();
var controller = new CustomerController(repository);// 通过外部控制Controller里面的依赖
var customer = new Model.Customer()
{
FirstName = "Mingson",
LastName = "Zheng",
Phone = "123456789",
};
var result = controller.Add(customer);
Assert.IsType<OkResult>(result);// 正确结果
var resultBad = controller.Add(customer);
Assert.IsType<BadRequestObjectResult>(resultBad);// 错误结果
通过单元测试可以得知修改Bug过程中是否误删代码,导致原来通过的测试现在无法通过。
任务20:DI初始化的源码解读
Microsoft.AspNetCore.Hosting.WebHostBuilder
/// <summary>
/// Builds the required services and an <see cref="T:Microsoft.AspNetCore.Hosting.IWebHost" /> which hosts a web application.
/// </summary>
public IWebHost Build()
{
......
// 第一步,build
IServiceCollection serviceCollection1 = this.BuildCommonServices(out hostingStartupErrors);
// 第二步,获取ServiceCollection,ServiceProvider
IServiceCollection serviceCollection2 = serviceCollection1.Clone();
IServiceProvider providerFromFactory = GetProviderFromFactory(serviceCollection1);
......
// 第三步,new一个WebHost,传入ServiceCollection,ServiceProvider
WebHost webHost = new WebHost(serviceCollection2, providerFromFactory, this._options, this._config, hostingStartupErrors);
......
// 第四步,webHost初始化方法Initialize
webHost.Initialize();
......
}