Simon Vane
Simon Vane

Reputation: 2014

Get service from WebApplicationFactory<T> in ASP.NET Core integration tests

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.

Upvotes: 39

Views: 18417

Answers (3)

mialkin
mialkin

Reputation: 2781

In APS.NET 6, 7 and 8 I had to use _factory.Services.CreateScope():

using var scope = _factory.Services.CreateScope();
var sender = scope.ServiceProvider.GetRequiredService<IEmailSender>();
await sender.SendAsync("Hello");

Upvotes: 11

Lam Le
Lam Le

Reputation: 1839

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();
}

Upvotes: 23

Aleksei
Aleksei

Reputation: 594

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>();
}

Upvotes: 45

Related Questions