繁体   English   中英

依赖项注入不适用于ASPNETCore.TestHost

[英]Dependancy Injection not working with ASPNETCore.TestHost

我一直在努力解决这个问题。 我的WebAPI应用程序在本地计算机和生产服务器上运行良好,但是在具有依赖项注入的控制器的集成测试期间失败。 一切看起来都很干净,我不知道为什么这不起作用。

下面是模块:控制器:

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

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

启动:

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

考试:

[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);                
}

如果我对此进行调试,则调试器甚至都不会进入控制器构造函数。 如果我注释掉构造函数并创建一个空的构造函数,那么一切都会很好,因此与依赖项注入有100%的关系。 请帮忙。 谢谢。


更新1

因此,这似乎是上下文初始化的问题,因为如果执行以下操作,则构造器也不会初始化。

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

因此,经过两夜的不眠之夜,我发现了问题...由于某些明显的原因,测试服务器无法使用以下命令从apsettings.json读取与我的数据库的连接字符串:

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

所以我所要做的就是

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

由于某种原因,这个错误不会出现在任何地方,或者也许我没有看到它,所以在我发现它说的很明显之后。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM