9
votes

How can I access the dbcontext of an in memory database inside an integration test?

I have followed the code here: https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#customize-webapplicationfactory

and have a similar test to:

public class IndexPageTests : 
    IClassFixture<CustomWebApplicationFactory<RazorPagesProject.Startup>>
{
    private readonly HttpClient _client;
    private readonly CustomWebApplicationFactory<RazorPagesProject.Startup> 
        _factory;

    public IndexPageTests(
        CustomWebApplicationFactory<RazorPagesProject.Startup> factory)
    {
        _factory = factory;
        _client = factory.CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            });
    }

In this IndexPageTests is it possible to access the in-memory dbcontext?

I have tried

 using (var context = new ApplicationDbContext(???))

I need to access data from tables i had previously seeded from CustomWebApplicationFactory

but not sure what to put for the options

2
You would have to resolve it via the host's services provider. factory.Server.Host.Services.GetService<ApplicationDbContext>() - Nkosi
@Nkosi, this gives error : Cannot resolve scoped service 'ApplicationDbContext' from root provider. - raklos
@Nikosi, thanks you pointed me in the right direction... had to create scope first _factory.Server.Host.Services.GetService<IServiceScopeFactory>(); - raklos
Glad to help. You should add it as a self answer so that others can benefit. - Nkosi

2 Answers

14
votes

Thanks to Nikosi, this is the way I managed to get the dbcontext

var scopeFactory = _factory.Server.Host.Services.GetService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
   var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
}
0
votes

The below worked with me as it didn't throw an exception:

var scope = factory.Services.GetService<IServiceScopeFactory().CreateScope();
var context =  scope.ServiceProvider.GetService<ApplicationDbContext();

Ref. https://github.com/dotnet/aspnetcore/issues/14424