在C#中通过反射访问多个项目的所有类型、类和接口

问题描述 投票:0回答:1

我要问的问题似乎有一个可靠的解决方案,但老实说我还没有找到它。考虑一个具有多个项目的 asp.net core Web api 应用程序,例如域层、应用程序服务、表示、基础设施等。在尝试通过反射(在表示层中)动态注册服务时,您需要访问应用程序服务层中定义的类型。反射似乎无法访问项目上的类型,并且仅限于正在使用的项目。我想知道您是否介意告诉我它基本上是如何完成的,或者最好的做法是什么,而不是解决 dll 文件。 非常感谢您的帮助!

c# asp.net entity-framework reflection
1个回答
0
投票

如果您想从其他程序集获取具有反射的类型,则需要使用

Assemly.Load("path_to_your_assembly")
例如:

  Assembly SampleAssembly = Assembly.Load
            ("SampleAssembly");
        // Display all the types contained in the specified assembly.
        foreach (Type oType in SampleAssembly.GetTypes()) {
            Console.WriteLine(oType.Name);

或更简单的方法是像这样使用

typeof()

Assembly SampleAssembly = typeof(SomeClassOrInterfaceInAssemblyThatYouWishToLoad).Assembly
 // Display all the types contained in the specified assembly.
            foreach (Type oType in SampleAssembly.GetTypes()) {
                Console.WriteLine(oType.Name);
© www.soinside.com 2019 - 2024. All rights reserved.