私はC#を勉強しています。Andrew Troelsen の「C# and the .NET Platform」と Jeffrey Richter の「CLR via C#」の本を読みました。現在、あるディレクトリからアセンブリをロードし、それらを AppDomain にプッシュし、含まれているメソッド (プラグインをサポートするアプリケーション) を実行するアプリケーションを作成しようとしています。これは、共通インターフェイスである DLL です。私はそれを自分のアプリケーションに追加し、プラグインを含むすべての DLL に追加します。MainLib.DLL
namespace MainLib
{
public interface ICommonInterface
{
void ShowDllName();
}
}
ここにプラグインがあります: PluginWithOutException
namespace PluginWithOutException
{
public class WithOutException : MarshalByRefObject, ICommonInterface
{
public void ShowDllName()
{
MessageBox.Show("PluginWithOutException");
}
public WithOutException()
{
}
}
}
もう 1 つ: PluginWithException
namespace PluginWithException
{
public class WithException : MarshalByRefObject, ICommonInterface
{
public void ShowDllName()
{
MessageBox.Show("WithException");
throw new NotImplementedException();
}
}
}
そして、ここに DLL をロードして別の AppDomain で実行するアプリケーションがあります。
namespace Plug_inApp
{
class Program
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(CreateDomainAndLoadAssebly, @"E:\Plugins\PluginWithException.dll");
Console.ReadKey();
}
public static void CreateDomainAndLoadAssebly(object name)
{
string assemblyName = (string)name;
Assembly assemblyToLoad = null;
AppDomain domain = AppDomain.CreateDomain(string.Format("{0} Domain", assemblyName));
domain.FirstChanceException += domain_FirstChanceException;
try
{
assemblyToLoad = Assembly.LoadFrom(assemblyName);
}
catch (FileNotFoundException)
{
MessageBox.Show("Can't find assembly!");
throw;
}
var theClassTypes = from t in assemblyToLoad.GetTypes()
where t.IsClass &&
(t.GetInterface("ICommonInterface") != null)
select t;
foreach (Type type in theClassTypes)
{
ICommonInterface instance = (ICommonInterface)domain.CreateInstanceFromAndUnwrap(assemblyName, type.FullName);
instance.ShowDllName();
}
}
static void domain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
}
}
}
別のドメインで実行するinstance.ShowDllName();
と (間違っているのでしょうか?)、未処理の例外が実行されているドメインをドロップしますが、デフォルトのドメインは機能します。しかし、私の場合、別のドメインで例外が発生した後、デフォルトのドメインがクラッシュします。私が間違っていることを教えてください。