想在 WebApplicationFactory 中抢在 Web 项目的 Startup.ConfigureServices 之前注册服务,尝试的代码如下
public class CustomeWebApplicationFactory : WebApplicationFactory<Startup>
{
protected override IHost CreateHost(IHostBuilder builder)
{
builder.ConfigureServices(services =>
{
services.AddCnblogsAuthentication(options => options.Cookie.Domain = "localhost");
});
return base.CreateHost(builder);
}
}
虽然 CreateHost 会在 Startup.ConfigureServices 之前执行,但 builder.ConfigureServices 中的 action 依然在 Startup.ConfigureServices 之后执行
通过 override CreateHostBuilder 解决了
public class CustomeWebApplicationFactory : WebApplicationFactory<Startup>
{
protected override IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddCnblogsAuthentication(options => options.Cookie.Domain = "localhost");
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
CreateHostBuilder 中不写 base.CreateWebHostBuilder()
,就不会执行 Web 项目 Program 中的 CreateHostBuilder