外部フォルダのアセンブリを動的にロードする

アプリケーションがおいてあるフォルダの外にあるアセンブリを、カレント AppDomain に動的にロードする方法。

ロードしようとしているアセンブリが見つからない場合に AppDomain.AssemblyResolve イベントが発生するので、このイベントのハンドラで追加のアセンブリロード処理を実装すればよい。

public class Bootstrap
{
private static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += SearchAssemblyFromDirectories;
string[] directories = new string[] { @"C:\asm" };
AppDomain.CurrentDomain.SetData("directories", directories);
Assembly asm = Assembly.Load("MyAssembly");
foreach (Type type in asm.GetTypes())
{
Console.WriteLine(type.FullName);
}
Console.ReadKey();
}

private static Assembly SearchAssemblyFromDirectories(object sender, ResolveEventArgs e)
{
string[] directories = (string[])AppDomain.CurrentDomain.GetData("directories");
foreach (string dir in directories)
{
string path = dir + "\\" + e.Name.Split(',')[0] + ".dll";
if (File.Exists(path))
{
return Assembly.LoadFrom(path);
}
}
return null;
}
}


これで exe がどこにあっても C:\asm フォルダにある MyAssembly.dll をロードできる。



業務アプリケーションだと使い道がなさそうだが、ILDASM とか Reflector のように、アセンブリを読み込んで中身を解析するようなツールを作る時には役立ちそうだ。

Comments

Popular posts from this blog

TFS: 別PCでのチェックアウトを取り消す

WPF の RichTextBox に文字列を設定する&取り出す

WPFアプリにアニメーションGIFを表示させる