Dependency Injection does not work with ASPNETCore.TestHost

I tried many hours with this problem. My WebAPI application works fine on the local computer and server, but does not work during the controller integration test, which has dependency injection. Everything looks very clean, and I have no idea why this is not working.

So, here are the modules: Controller:

public SurveyController(IBoatInspectorRepository<Survey> repository)
{
    _repository = repository;
}

[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] {"value1", "value2"};
}

Launch:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IBoatInspectorRepository<Survey>, BoatInspectorRepository<Survey>>();
}

Test:

[Test]
public async Task GetSurveyDb_NullReturn_ReturnNotFound()
{  
    using (var testServer = CreateTestServer())
    {
        var client = testServer.CreateClient();
        var value = await client.GetAsync("/api/survey/");
    }
}  

private TestServer CreateTestServer()
{
    var builder = new WebHostBuilder()                
        .UseStartup<Startup>()
        .ConfigureServices(services => 
            services.AddScoped<IBoatInspectorRepository<Survey>, BoatInspectorRepository<Survey>>());

    return new TestServer(builder);                
}

If I debug this, the debugger does not even go into the controller constructor. If I comment on the constructor and create an empty one, everything works fine, so 100% has something to do with dependency injection. Please help. Thank.


UPDATE 1

Thus, it seems that this is a problem with initializing the context, because if I do the following, the constructor also does not initialize.

    public SurveyController(BoatInspectorContext context)
    {
     //debuger doesn't go inside here so must be something with context   
    }
+1
1

, ... - db apsettings.json,

.AddDbContext<BoatInspectorContext>(
                opt=>opt.UseNpgsql(Configuration.GetConnectionString("BoatInspectorConnectionString")));

, ,

.AddDbContext<BoatInspectorContext>(
                opt => opt.UseNpgsql(
                    connectionString:
                    "my_magic_connection_string"));

- , , , , , .

0

Source: https://habr.com/ru/post/1688630/


All Articles