2

I know how to get all types that implement an interface such as using this code.

However I have not figured out why I can't make this work in my Asp.Net MVC ApiController. I have two projects (apologies for the naming convention. I created a solution from scratch just to make sure that my existing one was not the cause of the error):

.sln
-WebAPI
-ClassLibrary1
    -Interface1
    -Class1 : Interface1

WebApi has a project reference to ClassLibrary1.

Calling my ApiController it looks at the dlls in the bin directory. It is able to get ClassLibrary1.dll but when it tries to look at which type is assignable from Interface1 it does not find anything.

enter image description here

Code is just a .net mvc project and class library and hosted here

Community
  • 1
  • 1
Jan Navarro
  • 327
  • 4
  • 16

2 Answers2

1

You don't need to find referenced assembly by its path, you can just use the type to get its assembly as below:

    internal class Program
    {
        private static void Main(string[] args)
        {
            var type = typeof(Interface1);
            Assembly loadedAssembly = type.Assembly;
            var types = loadedAssembly.GetTypes().Where(c => type.IsAssignableFrom(c));

            foreach (var typeFound in types)
            {
                Console.WriteLine(typeFound.Name);
            }

            Console.ReadKey();
        }
    }

Output:

Interface1

Class1

Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
0

The problem is that you have the assembly ClassLibrary1 loaded twice and therefore ClassLibrary1.Interface1 from the reference is not the same interface as ClassLibrary1.Interface1 from the loaded assembly.

Move Interface1 to its own shared library and reference this shared library in both ClassLibrary1 and WebAPI to solve your problem.

About Assembly.LoadFile, this is fine if you're planning to make a plugin like system. This is not needed if you are referencing the library because then you can just enumerate the types from the already loaded assembly.

In that case you can use:

typeof(Interface1).Assembly.GetTypes().Where(c => typeof(Interface1).IsAssignableFrom(c));

as suggested by Bhushan Firake.

Community
  • 1
  • 1
huysentruitw
  • 27,376
  • 9
  • 90
  • 133
  • I accepted this as answer because I am doing a plugin like system and moving the reference to a shared library solved the issue. The other answer is helpful too. – Jan Navarro Sep 01 '15 at 01:23