Assembly.ReflectionOnlyLoadFrom not working

2019-04-22 19:07发布

I have an Assembly Library1.dll which contains some Interfaces, which were serialized as a byte array into the database. For some reasons we have to change the Interface properties and defintion. so now i am writing a migration utility. So i have 2 versions of Library1.dll , In my utility i have created a folder where i store the new version of Library1.dll . This utility in turn also references Library1.dll hence in bin folder contains Library1.dll but this dll is compiled on older version. My new version of Library1.dll is stored in a private path which i am passing to Assembly.ReflectionOnlyLoadFrom function to instantiate and hence GetTypes on the assembly loaded which further would enable me to do conversion of data.

But I always get ReflectionTypeLoadException when trying to load Library1.dll from private path.

Please help guys!!!. any help would be appreciated. I am really stuck.

Thanks, AG

1条回答
2楼-- · 2019-04-22 19:43

If your Library is referencing another dll, GetTypes will fail when it hits a type that uses an external type. Unlike normal assembly loading, ReflectionOnly Assembly loading will not resolve dependencies. You can either subscribe to AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve and load the dependencies as required, or you could pre-load them.

This is the code I use for this:

var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyPath);
foreach (var assemblyName in assembly.GetReferencedAssemblies()) {
  try {
    Assembly.ReflectionOnlyLoad(assemblyName.FullName);
  } catch {
    Assembly.ReflectionOnlyLoadFrom(Path.Combine(Path.GetDirectoryName(assemblyPath), assemblyName.Name + ".dll"));
  }
}

This will try to load all dependencies of the reflection-only loaded assembly first by fullname, then by path (assuming that the dependency is in the same directory as the loaded assembly).

查看更多
登录 后发表回答