I have the following project structure:
Web API
- Class Library
A
- Class Library
B
- Class Library
C
These are the references between the projects
Web API
directly referencesA
andB
B
directly referencesC
C
has a method which needs to ensure that A
is loaded to use, by reflection, a type defined in it.
My code actually is like the following
public class C {
public void MethodCallingBType( string fullClassName ) {
//e.g. "MyNamespace.MyType, MyNamespace"
string[] parts = fullClassName.Split( ',' );
var className = parts[0].Trim();
var assemblyName = parts[1].Trim();
if ( !string.IsNullOrEmpty( assemblyName ) && !string.IsNullOrEmpty( className ) ) {
string assemblyFolder = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );
string assemblyPath = Path.Combine( assemblyFolder, assemblyName + ".dll" );
if ( File.Exists( assemblyPath ) ) {
Assembly assembly = Assembly.LoadFrom( assemblyPath );
Type type = assembly.GetType( className );
result = Activator.CreateInstance( type ) as IInterfaceRunner;
}
}
}
}
This code actually does not work as the Path.GetDirectoryName
function does not return a valid path. Apart from this I would like to create a better way t ensure that B
module is loaded in memory before looking for its type.
Any suggestion?
The simple
Assembly.Load
does not work? You don't have to know the location, only the name.I use
Assembly.CodeBase
in the same situation and it works fine:Best regards, Peter
Modifying Peter's answer, but the logic is more correct as his will fail on the combine and no reason to create a URL to get the local file path.