Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all types that implement an interface in .NET Core

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.

like image 714
Mr. Robot Avatar asked Jul 18 '16 18:07

Mr. Robot


People also ask

Which types can implement an interface in C#?

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.

How many types of interface are there in C#?

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.

Do I have to implement all interface methods C#?

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.


1 Answers

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()
like image 79
littlewang Avatar answered Sep 19 '22 20:09

littlewang