Reputation:
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
Upvotes: 4
Views: 3660
Reputation:
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?)
Thus, I had to use this with Server added on, like this:
using (var scope = _factory.Server.Host.Services.CreateScope())
{
// do something
}
Upvotes: 2
Reputation: 239270
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
}
Upvotes: 3