在我们的 C# Azure 函数应用程序中,有时会遇到问题,有人向触发器使用的类添加新的依赖项,但忘记将其添加到 Program.cs/Startup.cs 中的 DI 容器中。应用程序仍将构建并启动,但运行 Azure 函数触发器时将引发异常。
我们如何确保在构建时、应用程序启动或测试时捕获此类错误,而不是在运行时捕获?
这是一个测试,验证是否可以创建触发器类,这意味着为所有直接和间接依赖项正确设置了 DI 注入。在本例中,我们有一个名为
IAzureTrigger
的接口,所有触发器类都实现该接口。 这个答案被用作起点。
[Test]
public void VerifyTriggerDependencyInjection()
{
using var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(Program.ConfigureServices)
.Build();
var triggerTypes = typeof(IAzureTrigger).Assembly.ExportedTypes.Where(
t => typeof(IAzureTrigger).IsAssignableFrom(t) && t.IsClass
);
var errors = new Dictionary<Type, Exception>();
foreach (var triggerType in triggerTypes)
{
try
{
ActivatorUtilities.CreateInstance(host.Services, triggerType);
}
catch (Exception e)
{
errors.Add(triggerType, e);
}
}
if (errors.Any())
{
Assert.Fail(
string.Join(
$"{Environment.NewLine}{Environment.NewLine}",
errors.Select(
x =>
$"Failed to resolve trigger {x.Key.Name} due to {x.Value.Message}{Environment.NewLine}{x.Value.InnerException?.Message ?? ""}"
)
)
);
}
}