![](/img/trans.png)
[英]dynamically resolving types from an Assembly loaded through Reflection
[英]FileNotFound when return Types[] from loaded assembly via reflection
我正在嘗試加載加載項程序集(放置在
D:\\ xyz \\ addin.dll
當我的應用程序在
D:\\ MyApp \\ MyApp.exe
這樣,不應鎖定插件文件,以便可以在應用程序運行時再次復制它的新版本。 為此,我創建了新的應用程序域並加載了包含AssembltLoader類的通用dll,然后調用AssemblyLoader加載了插件並獲取了所有可用的類型。 Addin dll的依賴項已放置在同一文件夾中。 現在從加載項dll獲取類型工作正常,但是當我
返回assembly.GetTypes();
一件非常奇怪的事情發生了。 它執行該行,但在該函數退出時會引發異常“ d:\\ xyz \\ addin.dll” FileNotFound
public class ObjectLoader : IDisposable
{
public Type[] GetAllTypesFromAssembly(string filePath)
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
setup.ShadowCopyFiles = "true";
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AssemblyLoader asemblyLoader = null;
AppDomain appDomain = AppDomain.CreateDomain(filePath, adevidence, setup);
appDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
domains.Add(filePath, appDomain);
object[] parms = { filePath };
BindingFlags bindings = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;
try
{
asemblyLoader = (AssemblyLoader)appDomain.CreateInstanceFromAndUnwrap(
setup.ApplicationBase +
"Common.dll", "Common.AssemblyLoader",
true, bindings, null, parms, null, null, null
);
}
catch (Exception ex)
{
throw ex; // new AssemblyLoadFailureException();
}
object types = null;
if (asemblyLoader != null)
{
// On following line i am facing the error which occur on following line but when GetAllTypes exits.
types = asemblyLoader.GetAllTypes();
}
return (Type[])types;
}
}
internal class AssemblyLoader : MarshalByRefObject, IDisposable
{
private Assembly assembly = null;
public object GetAllTypes()
{
BindingFlags flags = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;
object types = null;
if (assembly != null)
{
try
{
// following line works fine and loads a type (it contains one class)
types = assembly.GetTypes();
}
catch (Exception)
{
types = new ObjectLoadFailureException();
}
}
else
{
types = new AssemblyNotLoadedException();
}
return types;
}
}
這是異常詳細信息:
System.IO.FileNotFoundException was unhandled
HResult=-2147024894
Message=Could not load file or assembly 'AddIn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Source=mscorlib
FileName=AddIn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
FusionLog==== Pre-bind state information ===
LOG: DisplayName = AddIn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
(Fully-specified)
LOG: Appbase = file:///D:/MyApp/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
如果我同時在D:\\ xyz \\和D:\\ MyApp \\中復制我的addin.dll,則沒有錯誤。 我無法在運行時環境中執行此操作。
您正在將Type
對象編組到主AppDomain中。
這將導致CLR加載包含該AppDomain中的類型的程序集,從而導致此錯誤。
您可能根本不應該使用AppDomain。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.