Skip to content

Instantly share code, notes, and snippets.

@MrAntix
Created May 28, 2017 23:41
Show Gist options
  • Save MrAntix/f58f4ea3fcbde7e0e0f77fcd880cd292 to your computer and use it in GitHub Desktop.
Save MrAntix/f58f4ea3fcbde7e0e0f77fcd880cd292 to your computer and use it in GitHub Desktop.
Find Implementations In Same Assembly even generics
public static class ReflectionExtensions
{
public static void FindImplementationsInSameAssemblyAs<T>(
this Type type,
Action<Type, Type> action)
{
var assembly = typeof(T).GetTypeInfo().Assembly;
var query =
from implementationType in assembly.GetTypes()
let implementationTypeInfo = implementationType.GetTypeInfo()
where !implementationTypeInfo.IsInterface && !implementationTypeInfo.IsAbstract
from serviceType in implementationType.GetInterfaces()
where serviceType.IsAssignableFrom(type)
|| serviceType.IsGenericTypeDefinition(type)
|| serviceType.GetInterfaces().Any(i => i.IsGenericTypeDefinition(type))
select new {serviceType, implementationType};
foreach (var a in query)
{
Debug.WriteLine($"{a.serviceType} => {a.implementationType}");
action(a.serviceType, a.implementationType);
}
}
public static bool IsGenericTypeDefinition(
this Type type, Type otherType)
{
return type.GetTypeInfo().IsGenericType
&& type.GetGenericTypeDefinition() == otherType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment