Using reflection, How can I get all types that implement some specific interface in .NET Core? I have noticed that the methods usable in .NET 4.6 are not available anymore.
For example, this code doesn't work.
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
It throws The name 'AppDomain' does not exist in the current context
error.
In C# versions earlier than 8.0, an interface is like an abstract base class with only abstract members. A class or struct that implements the interface must implement all its members. Beginning with C# 8.0, an interface may define default implementations for some or all of its members.
Some of the interface types in C# include. IEnumerable − Base interface for all generic collections. IList − A generic interface implemented by the arrays and the list type. IDictionary − A dictionary collection.
Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.
you can do this way:
System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();
foreach (System.Reflection.TypeInfo ti in ass.DefinedTypes)
{
if (ti.ImplementedInterfaces.Contains(typeof(yourInterface)))
{
ass.CreateInstance(ti.FullName) as yourInterface;
}
}
If you want types in all assemblies, just simply use the following to get all the references and do the above again:)
ass.GetReferencedAssemblies()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With