c# - Api Controller 获取实现接口(interface)的所有类型

标签 c# asp.net-mvc-4 asp.net-web-api .net-assembly .net-reflector

我知道如何获取实现接口(interface)的所有类型,例如使用这个 code .

但是我还没有弄清楚为什么我不能在我的 Asp.Net MVC ApiController 中完成这项工作。我有两个项目(为命名约定道歉。我从头开始创建一个解决方案只是为了确保我现有的不是错误的原因):

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

WebApi 有一个对 ClassLibrary1 的项目引用。

调用我的 ApiController,它查看 bin 目录中的 dll。它能够获取 ClassLibrary1.dll,但是当它尝试查看可从 Interface1 分配的类型时,它找不到任何东西。

enter image description here

代码只是一个 .net mvc 项目和类库并托管 here

最佳答案

你不需要通过它的路径找到引用的程序集,你可以直接使用类型来获取它的程序集,如下所示:

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

输出:

接口(interface)1

1级

关于c# - Api Controller 获取实现接口(interface)的所有类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32265292/

相关文章:

sql-server - 带有我自己的数据库表和列的 ASP.NET MVC 4 安全架构

.net - 如何让 Web API OData v4 使用 DateTime

c# - 添加时出现 DbUpdateConcurrencyException

c# - 使用 Azure BrokeredMessage 在不知道类型的情况下获取正文

c# - 检测浏览器中是否弹出打开文件对话框

c# - grid.mvc 在 Controller 中使用过滤结果

c# - 如何在 Web Api 中发布自定义命名方法?

c# - 简易喷油器 : RegisterWebApiController failing to suppress DisposableTransientComponent warning

c# - 为引用 UI 控件的类编写单元测试

c# - 对用户单击已选择的ListViewItem,MVVM使用react