[英]Dependancy Injection not working with ASPNETCore.TestHost
I have been struggling many hours with this issue. 我一直在努力解决这个问题。 My WebAPI App works fine on local machine and production server but fails during an integration test of a controller that has dependency injection.
我的WebAPI应用程序在本地计算机和生产服务器上运行良好,但是在具有依赖项注入的控制器的集成测试期间失败。 Everything looks very clean and I have no idea why this is not working.
一切看起来都很干净,我不知道为什么这不起作用。
So here come the modules: The controller: 下面是模块:控制器:
public SurveyController(IBoatInspectorRepository<Survey> repository)
{
_repository = repository;
}
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] {"value1", "value2"};
}
The start up: 启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IBoatInspectorRepository<Survey>, BoatInspectorRepository<Survey>>();
}
The 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 doesn't even go into the controller constructor. 如果我对此进行调试,则调试器甚至都不会进入控制器构造函数。 If I comment out the constructor and create an empty one everything works fine so it is 100% something to do with the dependency injection.
如果我注释掉构造函数并创建一个空的构造函数,那么一切都会很好,因此与依赖项注入有100%的关系。 Please help.
请帮忙。 Thank you.
谢谢。
UPDATE 1 更新1
So it seems that it is a problem with context initialization because if I do the following the constructor isn't initialized either. 因此,这似乎是上下文初始化的问题,因为如果执行以下操作,则构造器也不会初始化。
public SurveyController(BoatInspectorContext context)
{
//debuger doesn't go inside here so must be something with context
}
So after two sleepless nights I found the fault... For some unovious reason the test server was not able to read the connection string to my db from apsettings.json using 因此,经过两夜的不眠之夜,我发现了问题...由于某些明显的原因,测试服务器无法使用以下命令从apsettings.json读取与我的数据库的连接字符串:
.AddDbContext<BoatInspectorContext>(
opt=>opt.UseNpgsql(Configuration.GetConnectionString("BoatInspectorConnectionString")));
so all I had to to was 所以我所要做的就是
.AddDbContext<BoatInspectorContext>(
opt => opt.UseNpgsql(
connectionString:
"my_magic_connection_string"));
For some reason this error wasn't coming up anywhere or maybe I didn't see it so after I spoted what it said it was pretty obvious. 由于某种原因,这个错误不会出现在任何地方,或者也许我没有看到它,所以在我发现它说的很明显之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.