I want to set up my tests using WebApplicationFactory<T>
as detailed in Integration tests in ASP.NET Core.
Before some of my tests I need to use a service configured in the real Startup class to set things up. The problem I have is that I can't see a way to get a service from the factory.
I could get a service from factory.Server
using factory.Host.Services.GetRequiredService<ITheType>();
except that factory.Server
is null until factory.CreateClient();
has been called.
Is there any way that I am missing to get a service using the factory?
Thanks.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With