たとえば、数値の平方根を計算する方法がたくさんあるとします。
ある開発者は自分の.dll (maths1.dll) をくれ、別の開発者は自分の .dll (maths2.dll) をくれて、3 番目の開発者 (maths3.dll) もくれます。
それらはすべて同じクラスを含み、同じインターフェースを実装しています。
アセンブリ 1 Maths1.dll
public class Maths : IMaths {
public static string Author = "Author1";
public static SquareRoot(int number) {
// Implementation method 1
}
}
アセンブリ 2 Maths2.dll
public class Maths : IMaths {
public static string Author = "Author2";
public static SquareRoot(int number) {
// Implementation method 2
}
}
などなど
そして、実行時にすべてのdllを動的に認識しなければならないコンソールアプリケーションがあります。
コード内で .dll ファイルを探すのは望ましくありません。
// DON'T WANT THIS
DirectoryInfo di = new DirectoryInfo("bin");
FileInfo[] fi = di.GetFiles("*.dll");
私の考えは、カスタム構成セクションを使用してapp.configファイルからそれらを管理することです。
<configuration>
<configSections>
<section name="MathsLibraries" type="MyMathsLibrariesSectionClass, ApplicationAssembly" />
</configSections>
<MathsLibraries>
<Library author="Author1" type="MathsClass, Maths1Assembly" /><!-- Maths1.dll -->
<Library author="Author2" type="MathsClass, Maths2Assembly" /><!-- Maths2.dll -->
<Library author="Author3" type="MathsClass, Maths3Assembly" /><!-- Maths3.dll -->
</MathsLibraries>
</configuration>
ライブラリ ファイルMaths1.dllをアプリケーションのbinフォルダーに手動でコピーすることを考慮して、 MathsLibrariesセクションのapp.configファイルに行を追加するだけです。
動的にリンクされたすべての .dll をユーザーに提示し、選択したライブラリを使用して数値の平方根を計算できるようにする、コンソール アプリケーションのMainのサンプル コードが必要です。
// NOT WORKING CODE, JUST IDEA OF WHAT IS NEEDED
public static void Main(string[] args) {
// Show the user the linked libraries
MathsLibraries libs = MathsLibraries.GetSection();
Console.WriteLine("Available libraries:");
foreach (MathLibrary lib in libs.Libraries) {
Console.WriteLine(lib.Author);
}
// Ask for the library to use
Console.Write("Which do you want to use?");
selected_option = Console.Read();
IMaths selected_library;
// since we don't know wich class would be,
// declare a variable using the interface we know they al implement.
// Assign the right class to the variable
if (selected_option == '1') {
selected_library = Assembly1.Maths;
} else if (selected_option == '2') {
selected_library = Assembly2.Maths;
}
// other options...
// Invoke the SquareRoot method of the dynamically loaded class
float sqr_result = selected_library.SquareRoot(100);
Console.WriteLine("Result is {0}", sqr_result);
Console.WriteLine("Press Enter key to exit");
Console.Read();
}
app.config からアセンブリをロードするこのタスクで誰か助けてください。
詳細なコードをいただければ幸いです。
ありがとう!