FromServices 无法与 WebApplicationFactory 一起使用<Program>

问题描述 投票:0回答:1

我使用 Asp.net core 8 进行了以下 NUnit 测试。

public class DevextremeTests 
{
    private WebApplicationFactory<Program> _factory;

    public DevextremeTests()
    {
        _factory = new WebApplicationFactory<Program>();
    }

    [Test]
    public void Can_get_grid()
    {
        using (var scope = _factory.Services.CreateScope())
        {
            var scopedServices = scope.ServiceProvider;
            var companyServices = scopedServices.GetRequiredService<CompanyServices>(); //not null
            var autoQuery = scopedServices.GetRequiredService<IAutoQueryDb>(); //not null
            // companyServices.AutoQuery is null 
        }
    }
}

companyServices
已填充,但该服务上还有其他服务,例如

[FromServices]
public IAutoQueryDb AutoQuery { get; set; } //null
[FromServices]
public ApplicationDbContext Ef { get; set; } //null

在主应用程序中,嵌套服务加载良好。

如果我从使用

[FromServices]
切换到构造函数注入,那么它就会起作用并且嵌套服务会填充。

为什么

[FromServices]
不能与
WebApplicationFactory<Program>()
一起使用?

c# asp.net-core .net-8.0
1个回答
0
投票

因为

FromServicesAttribute
提供了ASP.NET Core特定的绑定:

指定应使用 request 服务绑定参数或属性。

内置DI不支持属性注入:

我们建议使用内置容器,除非您需要它不支持的特定功能,例如:

  • 房产注入
  • ...

通过该属性的机制是特定于控制器操作的 ASP.NET 请求或基于每个请求的 Razor 页面。而且你这里没有请求,只是一个普通的 DI 容器。

© www.soinside.com 2019 - 2024. All rights reserved.