Net Core: Find Services from WebApplicationFactory

2019-08-21 11:40发布

问题:

How do I grab all the Services from a CustomWebApplicationFactory? Startup class has conducted dependency injection for IDepartmentRepository and IDepartmentAppService. Would like to grab the new DI repository or service.

We are creating integration test which points to original application startup.

namespace Integrationtest
{
    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
            {
                var type = typeof(TStartup);
                var path = @"C:\\OriginalApplicationWebAPI";

                configurationBuilder.AddJsonFile($"{path}\\appsettings.json", optional: true, reloadOnChange: true);
                configurationBuilder.AddEnvironmentVariables();
            });
        }
    }
}

public class DepartmentAppServiceTest : IClassFixture<CustomWebApplicationFactory<OriginalApplication.Startup>>

{
    public testDbContext context;
    private readonly HttpClient _client;

    public DepartmentAppServiceTest(CustomWebApplicationFactory<OriginalApplication.Startup> factory)
    {
        _client = factory.CreateClient();
        factory.  // trying to find services here for IDepartmentRepository 
    }

https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api

回答1:

It's factory.Host.Services. Don't forget that you'll need to create a scope to access scoped services such as your context:

using (var scope = _factory.Host.Services.CreateScope())
{
    var foo = scope.ServiceProvider.GetRequiredService<Foo>();
    // do something
}


回答2:

Received Error:

'CustomWebApplicationFactory' does not contain a definition for 'Host' and no accessible extension method 'Host' accepting a first argument of type 'CustomWebApplicationFactory' could be found (are you missing a using directive or an assembly reference?) so I had to use this with Server added on.

using (var scope = _factory.Server.Host.Services.CreateScope())
{
    // do something
}