I want to get all Types from Solution who inherit specify class. My Solution structure looks like:
AssemblyTest (Solution)
|
- ProjectOne (Class Library)
- - BaseClass.cs (Class)
|
- ProjectTwo (Class Library)
- - FirstExampleClass.cs (Class inherit from BaseClass )
|
- ConsoleApp (Console Application)
- - SecondExampleClass.cs (Class inherit from BaseClass )
- - Program.cs (Class inherit from BaseClass )
In Program.cs
I want to get all Types who inherit BaseClass
. For this, i use code:
var typesList = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(p => p.GetTypes()
.Where(t => typeof(BaseClass)
.IsAssignableFrom(t) && !t.IsAbstract && t.IsPublic && t != typeof(BaseClass)));
But in typesList
i get only one element -> SecondExampleClass
from this same Project where exist Program.cs
.
BaseClass.cs
public class BaseClass{}
FirstExampleClass.cs
public class FirstExampleClass : BaseClass{}
SecondExampleClass.cs
public class SecondExampleClass: BaseClass{}
P.S. ConsoleApp
project has reference to ProjectTwo
reference
CodePudding user response:
It's because the assemblies probably aren't loaded into the current AppDomain yet.
AppDomain.GetAssemblies()
gives you all assemblies which have already been loaded into the current AppDomain.BuildManager.GetReferencedAssemblies()
(This method is only available in the .Net Framework System.Web.dll) returns a list of all assemblies referenced from Web.config and elsewhere, and it loads those assemblies into the current AppDomain.
See Difference between AppDomain.GetAssemblies and BuildManager.GetReferencedAssemblies