我需要为我的解决方案创建一个新的AppDomain,以便可以从其自己的AppDomain中调用该方法。我的解决方案的所有相关.dll文件都已使用Fody / Costura嵌入到my.exe中。我创建了一个Loader : MarshalByRefObject
类来调用我的方法,但是当我在运行时执行加载程序时,出现以下异常:
无法加载文件或程序集'my.Assembly,版本为1.9.1.7242.23931,Culture = neutral,PublicKeyToken = null'或其依赖项之一。该系统找不到指定的文件。
代码正在我的AppDomain.CurrentDomain.BaseDirectory中寻找.dll文件,以通过加载程序执行我的方法,但它们不存在,但嵌入在可执行文件中。是否有一种方法让我的新AppDomain知道已嵌入到我的可执行文件中的程序集,而不必从BaseDirectory中加载它们?
我一直在寻找将其他程序集加载到我的新AppDomain中的方法,但是还没有找到一种方法。我还怀疑可能有Fody / Costura API可以执行此操作,但还没有找到适用于这种情况的任何内容。
internal class Loader : MarshalByRefObject
{
object CallInternal(string dll, string typename, string method, object[] parameters)
{
Assembly a = Assembly.LoadFile(dll);
Type t = a.GetType(typename);
MethodInfo m = t.GetMethod(method);
Console.WriteLine("Invoking " + m.Name);
return m.Invoke(null, parameters);
}
public static object Call(string dll, string typename, string method, params object[] parameters)
{
object result = null;
try
{
AppDomain newAppDomain = AppDomain.CreateDomain("myNewDomain", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);
Loader ld = (Loader)newAppDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Loader).FullName); //DLL file not found exception thrown from here
result = (Loader)ld.CallInternal(dll, typename, method, parameters);
AppDomain.Unload(newAppDomain);
}
catch (Exception ee)
{
Console.WriteLine("Exception Message [" + ee.Message + "]");
PDFUtil.Report.ErrSilent(ee);
}
return result;
}
}
我希望实例化我的Loader类,而无需在运行时从磁盘加载.dll。 Fody / Costura嵌入式.dll是否可能?
string resName = null;
foreach (string resourceName in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
Console.WriteLine("Assembly.GetExecutingAssembly().GetManifestResourceNames() [" + resourceName + "] ");
if (resourceName.Contains("my.Assembly"))
{
resName = resourceName;
Console.WriteLine("CurrentDomain Assembly my.Assembly [" + "] Resource name [" + resName + "]");
}
}
Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resName);
if (s != null)
{
byte[] data = new BinaryReader(s).ReadBytes((int)s.Length);
Assembly a = Assembly.Load(data);
newAppDomain.Load(data);
foreach (Assembly cdAssem in newAppDomain.GetAssemblies())
{
Console.WriteLine("newAppDomain Assembly 2 [" + cdAssem.GetName().FullName + "]");
}
}
我可以看到该程序集是新AppDomain的一部分:newAppDomain程序集2 [mscorlib,版本= 4.0.0.0,区域性=中性,PublicKeyToken = b77a5c561934e089]newAppDomain程序集2 my.Assembly版本= 1.9.1.7243.19014,文化=中性,PublicKeyToken =空]
但是使用CreateInstanceAndUnwrap()仍然无法说找不到my.Assembly.dll。我想知道是否可以将程序集加载到AppDomain中的唯一方法是从基本目录中加载程序集?