asp.net-coreasp.net-core-mvcasp.net-core-webapiasp.net-core-2.1

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.


Solution

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