如何验证ASP.NET Core中的DI容器? [英] How do I validate the DI container in ASP.NET Core?
问题描述
在我的 Startup
类中,我使用 ConfigureServices(IServiceCollection services)
方法来设置服务容器,并使用Microsoft的内置DI容器.Extensions.DependencyInjection .
In my Startup
class I use the ConfigureServices(IServiceCollection services)
method to set up my service container, using the built-in DI container from Microsoft.Extensions.DependencyInjection
.
我想在单元测试中验证依赖关系图以检查是否可以构造所有服务,以便我可以修复单元测试期间丢失的所有服务,而不是使应用程序在运行时崩溃.在以前的项目中,我使用了Simple Injector,该容器具有 .Verify()
方法.但是我找不到与ASP.NET Core类似的东西.
I want to validate the dependency graph in an unit test to check that all of the services can be constructed, so that I can fix any services missing during unit testing instead of having the app crash at runtime. In previous projects I've used Simple Injector, which has a .Verify()
method for the container. But I haven't been able to find anything similar for ASP.NET Core.
是否有任何内置(或至少推荐)的方法来验证整个依赖图是否可以构建?
(我能想到的最愚蠢的方法是这样的,但是由于框架本身注入了开放的泛型,它仍然会失败):
(The dumbest way I can think of is something like this, but it will still fail because of the open generics that are injected by the framework itself):
startup.ConfigureServices(serviceCollection);
var provider = serviceCollection.BuildServiceProvider();
foreach (var serviceDescriptor in serviceCollection)
{
provider.GetService(serviceDescriptor.ServiceType);
}
推荐答案
ASP.NET Core 3中添加了一个内置的DI容器验证,并且默认情况下仅在 Development
环境中启用了该验证.如果缺少某些内容,则容器在启动时会引发致命异常.
A built-in DI container validation was added in ASP.NET Core 3 and it is enabled only in the Development
environment by default. If something is missing, the container throws a fatal exception on startup.
请记住,默认情况下不会在DI容器中创建控制器,因此,典型的Web应用程序在此检查不会获得很多收益,除非将控制器注册到DI中:
Keep in mind that controllers aren't created in the DI container by default, so a typical web app won't get much from this check until the controllers are registered in the DI:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddControllersAsServices();
}
要禁用/自定义验证,请添加 IHostBuilder.UseDefaultServiceProvider
调用:
To disable/customize the validation, add a IHostBuilder.UseDefaultServiceProvider
call:
public class Program
{
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
//...
.UseDefaultServiceProvider((context, options) =>
{
options.ValidateOnBuild = false;
});
This validation feature has several limitations, read more here: https://andrewlock.net/new-in-asp-net-core-3-service-provider-validation/
这篇关于如何验证ASP.NET Core中的DI容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!