Getting All Types That Implement an Interface

Getting all types that implement an interface

Mine would be this in c# 3.0 :)

var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));

Basically, the least amount of iterations will always be:

loop assemblies  
loop types
see if implemented.

C# Iterate through all classes implementing interface

So i got the solution with the help of @StevenWiliams and @JimWolff

For anyone who for some reason has the same problem, here is my udated code:

IEnumerable<Type> _commands = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).Where(t => t.GetInterfaces().Contains(typeof(ICommand)));
foreach (Type _type in _commands)
{
ICommand _command = (ICommand)Activator.CreateInstance(_type);
Debug.Log("Name: " + _command.name);
}

The problem I faced was, that I forgot, that classes can have multiple instances and therefor i cant get the value of the class directly. Creating an instance fixes this problem.

Again, credits to @StevenWiliams and @JimWolff.

Getting all types that implement an interface in .NET Core

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()

Get all implementations types of a generic interface

You can try working example.

Declarations:

public interface IEntity { }
public class Entity1 : IEntity { }
public class Entity2 : IEntity { }

public interface IEntityModelBuilder<out T> where T : IEntity { }

public class BaseClass1 : IEntityModelBuilder<Entity1>
{
public BaseClass1(int a) { }
}
public class BaseClass2 : IEntityModelBuilder<Entity2>
{
public BaseClass2(int a) { }
}

Usage:

List<IEntityModelBuilder<IEntity>> objects = Assembly.GetExecutingAssembly().GetTypes()
.Where(x => x.GetInterfaces().Any(y => y.IsGenericType && && y.Name == "IEntityModelBuilder`1"))
.Select(x => (IEntityModelBuilder<IEntity>)Activator.CreateInstance(x, new object[] { 0 })).ToList();

Get all classes that implement an interface and call a function in .NET Core

Since it's always null I think that the problem is that you're not creating an instance of your handler. I prepared a demo for you where I did that and it works.

public interface ICommandHandler 
{
string Command { get; }
Task ExecuteAsync();
}
public class FirstCommandHandler : ICommandHandler
{
public string Command => "First";

public async Task ExecuteAsync()
{
Console.WriteLine("Hello from first.");
await Task.Delay(10);
}
}
public class SecondCommandHandler : ICommandHandler
{
public string Command => "Second";

public async Task ExecuteAsync()
{
Console.WriteLine("Hello from second.");
await Task.Delay(10);
}
}

public class Program
{
static async Task Main(string[] args)
{
var handlers = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => typeof(ICommandHandler).IsAssignableFrom(p) && p.IsClass);

foreach (var handler in handlers)
{
var handlerInstance = (ICommandHandler)Activator.CreateInstance(handler);
if (handlerInstance.Command == "First")
{
await handlerInstance.ExecuteAsync();
}
}
}
}

If it's not the case, could you show some more code? Are you trying to check Command value by reflection?

C# find all class implement interface without generic type

The problem is that no class/ interface will extend the generic interface directly, they will all extend an instantiation of the generic interface for a given type parameter ( be it a concrete type such as string or another type parameter). You need to check if any of the interfaces a class implements are instances of the generic interface:

class Program
{
static void Main(string[] args)

{
var type = typeof(IWork<>);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => p.GetInterfaces().Any(i=> i.IsGenericType && i.GetGenericTypeDefinition() == type))
.ToArray();

// types will contain GenericClass, Cls2,Cls,DerivedInterface defined below
}
}

public interface IWork<T>
{
void Work(object session, T json);
}

class GenericClass<T> : IWork<T>
{
public void Work(object session, T json)
{
throw new NotImplementedException();
}
}
class Cls2 : IWork<string>
{
public void Work(object session, string json)
{
throw new NotImplementedException();
}
}
class Cls : GenericClass<string> { }

interface DerivedInterface : IWork<string> { }

Get all c# Types that implements an interface first but no derived classes

Firstly, I'd use Type.IsAssignableFrom rather than GetInterfaces, but then all you need to do is exclude types whose parent type is already in the set:

var allClasses = types.Where(type => typeof(IFace).IsAssignableFrom(type))
.ToList(); // Or use a HashSet, for better Contains perf.
var firstImplementations = allClasses
.Except(allClasses.Where(t => allClasses.Contains(t.BaseType)));

Or as noted in comments, equivalently:

var firstImplementations = allClasses.Where(t => !allClasses.Contains(t.BaseType));

Note that this will not return a class which derives from a class which implements an interface, but reimplements it.

How to find all the classes which implement a given interface?

A working code-sample:

var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(ISomething))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as ISomething;

foreach (var instance in instances)
{
instance.Foo(); // where Foo is a method of ISomething
}

Edit Added a check for a parameterless constructor so that the call to CreateInstance will succeed.



Related Topics



Leave a reply



Submit