最後に、いくつかの小さな変更といくつかの省略を修正したことを除いて、raboofが提案した方法とほぼ同じ方法で(およびdgvidが提案した方法と同様に)実行しました。この方法を選択したのは、最初に探していたものに最も近く、サードパーティの実行可能ファイルなどを使用する必要がなかったからです。それはうまくいきます!
これは私のコードが最終的に次のようになったものです:
編集: この関数を別のアセンブリに移動して、複数のファイルで再利用できるようにすることにしました (Assembly.GetExecutingAssembly() を渡すだけです)。
これは、組み込みの dll を含むアセンブリを渡すことができる更新バージョンです。
embeddedResourcePrefix は、埋め込みリソースへの文字列パスです。通常は、アセンブリの名前の後に、リソースを含む任意のフォルダー構造が続きます (例: dll がプロジェクト内の Resources というフォルダーにある場合は、"MyComapny.MyProduct.MyAssembly.Resources")。 )。また、dll の拡張子が .dll.resource であることも前提としています。
public static void EnableDynamicLoadingForDlls(Assembly assemblyToLoadFrom, string embeddedResourcePrefix) {
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { // had to add =>
try {
string resName = embeddedResourcePrefix + "." + args.Name.Split(',')[0] + ".dll.resource";
using (Stream input = assemblyToLoadFrom.GetManifestResourceStream(resName)) {
return input != null
? Assembly.Load(StreamToBytes(input))
: null;
}
} catch (Exception ex) {
_log.Error("Error dynamically loading dll: " + args.Name, ex);
return null;
}
}; // Had to add colon
}
private static byte[] StreamToBytes(Stream input) {
int capacity = input.CanSeek ? (int)input.Length : 0;
using (MemoryStream output = new MemoryStream(capacity)) {
int readLength;
byte[] buffer = new byte[4096];
do {
readLength = input.Read(buffer, 0, buffer.Length); // had to change to buffer.Length
output.Write(buffer, 0, readLength);
}
while (readLength != 0);
return output.ToArray();
}
}