Skip to content

Instantly share code, notes, and snippets.

@arphox
Last active September 9, 2022 17:07
Show Gist options
  • Save arphox/07e4af629028eef0378d6c11da466139 to your computer and use it in GitHub Desktop.
Save arphox/07e4af629028eef0378d6c11da466139 to your computer and use it in GitHub Desktop.
Azure Functions DependencyRegistrationChecker
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);
}
}
@arphox
Copy link
Author

arphox commented Sep 9, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment