Last active
September 9, 2022 17:07
-
-
Save arphox/07e4af629028eef0378d6c11da466139 to your computer and use it in GitHub Desktop.
Azure Functions DependencyRegistrationChecker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using FluentAssertions; | |
using Microsoft.Azure.Functions.Extensions.DependencyInjection; | |
using Microsoft.Extensions.DependencyInjection; | |
using Moq; | |
using Xunit; | |
namespace MyUnitTestProject; | |
public sealed class DependencyRegistrationChecker | |
{ | |
private readonly ServiceProvider _serviceProvider; | |
public DependencyRegistrationChecker() | |
{ | |
Startup startup = new(); // reference your function app's namespace for this to work | |
IServiceCollection serviceCollection = new ServiceCollection(); | |
IFunctionsHostBuilder functionsHostBuilder = Mock.Of<IFunctionsHostBuilder>( | |
x => x.Services == serviceCollection); | |
startup.Configure(functionsHostBuilder); | |
_serviceProvider = serviceCollection.BuildServiceProvider(); | |
} | |
[Theory] | |
[MemberData(nameof(DataForCheckDependenciesRegistered))] | |
public void CheckDependenciesRegistered(Type type) | |
{ | |
IEnumerable<Type> constructorParameterTypes = type | |
.GetConstructors() | |
.SelectMany(c => c.GetParameters()) | |
.Select(p => p.ParameterType); | |
foreach (Type parameterType in constructorParameterTypes) | |
{ | |
Action act = () => _serviceProvider.GetRequiredService(parameterType); | |
act.Should().NotThrow($"ServiceType: {type.Name}"); | |
} | |
} | |
public static IEnumerable<object[]> DataForCheckDependenciesRegistered() | |
{ | |
return typeof(Startup).Assembly | |
.GetTypes() | |
.Where(type => !IsException(type) && | |
HasCustomConstructor(type)) | |
.Select(type => new object[] { type }); | |
} | |
private static bool IsException(Type type) | |
{ | |
while (type != null && type.BaseType != typeof(object)) | |
{ | |
type = type.BaseType; | |
} | |
return type == typeof(Exception); | |
} | |
private static bool HasCustomConstructor(Type type) | |
{ | |
return type.GetConstructors() | |
.Any(constructor => constructor.GetParameters().Length > 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mentioned here:
Azure/azure-functions-host#6587 (comment)