代码之家  ›  专栏  ›  技术社区  ›  Guerrilla

FromServices无法使用WebApplicationFactory<Program>

  •  2
  • Guerrilla  · 技术社区  · 5 月前

    我使用Asp.net内核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] 到构造函数注入,它就会工作,嵌套的服务就会填充。

    为什么 [来自服务] 不使用 WebApplicationFactory<Program>() ?

    1 回复  |  直到 5 月前
        1
  •  2
  •   Guru Stron    5 月前

    因为 FromServicesAttribute 提供ASP。NET核心特定绑定:

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

    内置DI不 support property injection :

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

    • 房地产注入
    • ...

    通过属性的机制是ASP。NET Core请求特定于 controller actions , minimal API handlers Razor pages 基于每个请求(即web请求)。这里没有请求,只有一个“普通”DI容器。