dimanche 28 février 2016

Loading library dynamically

I have the following project structure:

  1. Web API
  2. Class Library A
  3. Class Library B
  4. Class Library C

These are the references between the projects

  • Web API directly references A and B
  • B directly references C

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 = m.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 IMechanicRunner;
            }
        }
    }
}

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?





Aucun commentaire:

Enregistrer un commentaire