Created
May 28, 2017 23:41
-
-
Save MrAntix/f58f4ea3fcbde7e0e0f77fcd880cd292 to your computer and use it in GitHub Desktop.
Find Implementations In Same Assembly even generics
This file contains hidden or 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
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