Get service from WebApplicationFactory<T> in ASP.NET Core integration tests
You need to create a scope from service provider to get necessary service:
using (var scope = AppFactory.Server.Host.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<MyDatabaseContext>();
}
Please pardon me. I know you ask for Net Core 2.1, but since v3.1+ people got here as well...
My project uses Net Core 3.1. When I use AppFactory.Server.Host.Services.CreateScope()
like Alexey Starchikov's suggestion, I encounter this error.
The TestServer constructor was not called with a IWebHostBuilder so IWebHost is not available.
Noted here, by designs.
So I use the below approach. I put database seeding in the constructor of the test class. Note that, I do not have to call factory.CreateClient()
. I create client variables in test methods as usual.
using (var scope = this.factory.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>();
// Seeding ...
dbContext.SaveChanges();
}