简体   繁体   English

在启动时验证 DI 容器

[英]Validate DI container at startup

I'd like to validate my DI container (aka check if I haven't forgotten to add a DI registration in my Startup class) at the very start of the application.我想在应用程序开始时验证我的 DI 容器(也就是检查我是否没有忘记在 Startup 类中添加 DI 注册)。 Meaning, once all the services are added, I'd like to try and resolve each one of them so that the application throws an exception if I forgot one.意思是,一旦添加了所有服务,我想尝试解决每个服务,以便应用程序在我忘记一个时抛出异常。

Naturally, I'd like to do this only in DEBUG mode.自然,我只想在调试模式下执行此操作。 For the default NET Core DI container, I can iterate through services and try to resolve them all (as in the case below), but how do I do that through Autofac (preferrably in ConfigureContainer )?对于默认的 NET Core DI 容器,我可以遍历服务并尝试将它们全部解析(如下例所示),但是如何通过 Autofac(最好在ConfigureContainer中)做到这一点?

#if DEBUG
    var sp = services.BuildServiceProvider();
    foreach (var item in services)
    {
        _ = sp.GetRequiredService(item.ServiceType);
    }
#endif

Autofac does not offer container registration validation and has no plans to do so in the near future. Autofac 不提供容器注册验证,并且在不久的将来也没有这样做的计划。 The issue I linked there explains why, but the long and the short of it is - since so many things can come from lambdas and dynamic code, there's too much that can't be validated.我在那里链接的问题解释了原因,但它的长短是 - 因为很多东西可以来自 lambdas 和动态代码,所以有太多无法验证的东西。 It seemed like the false positives or the "we validated 50% of the container but not the other 50% because it's dynamic" would give people a false sense of security, or, more likely, just make people angry that the results weren't correct.似乎误报或“我们验证了 50% 的容器,但没有验证其他 50%,因为它是动态的”会给人们一种错误的安全感,或者更有可能只是让人们对结果不正确感到愤怒正确的。 "My container validated but this thing failed! Autofac sucks!" “我的容器经过验证,但是这件事失败了!Autofac 很烂!”

On the other hand, Autofac 6.0 introduced a robust diagnostics mechanism for troubleshooting and tracing issues.另一方面, Autofac 6.0 引入了强大的诊断机制,用于故障排除和跟踪问题。 If you encounter issues, this can make it easier to figure out why.如果您遇到问题,这可以更容易找出原因。

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

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