Windows サービスを柔軟に管理するサービスマネージャの製作:パート1 - japan.internet.com デベロッパー
Windows サービスを柔軟に管理するサービスマネージャの製作:パート2 - japan.internet.com デベロッパー
AppDomain、AppDomainSetupの使用方法が分かるサンプルがある。
// create the service app domain
AppDomain svcDomain = null;
try
{
AppDomainSetup setup = new AppDomainSetup();
// use the process base directory as the new domain base and bin path
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
setup.PrivateBinPath = setup.ApplicationBase;
// use the assembly full name as friendly name
setup.ApplicationName = asmName.FullName;
// the base will be the shadow copy 'from' directory
setup.ShadowCopyDirectories = setup.ApplicationBase;
// enable shadow copying
setup.ShadowCopyFiles = "true";
// create the domain with no CAS evidence
svcDomain = AppDomain.CreateDomain(asmName.FullName, null, setup);
}
catch (Exception ex)
{
Logger.LogException(
new ApplicationException(
String.Format("Could not create an AppDomain for '{0}'; bypassing that assembly.",
asmName.FullName), ex));
return;
}
// Get remote service handler
RemoteServiceHandler svc = null;
try
{
// This call will actually create an instance
// of the service handler in the service domain
// and return a remoting proxy for us to act on.
// This is important because we don't want to
// load any type info from the service assembly
// into this assembly
svc = (RemoteServiceHandler)
svcDomain.CreateInstanceFromAndUnwrap(
svcDomain.BaseDirectory + "\\ServiceBroker.dll",
"ServiceBroker.RemoteServiceHandler");
}
catch (Exception ex)
{
// unload domain
AppDomain.Unload(svcDomain);
Logger.LogException(
new AssemblyLoadException(
"Could not load ServiceBroker remote service handler, bypassing that file.",
asmName.FullName, ex));
return;
}
これは、被管理サービスの実行に使う新しいAppDomainをセットアップするコードです。AppDomainSetupオブジェクトを使用しているのは、AppDomain.CreateDomainのオーバーロードにはないオプションがあるためです。ここでは、ディレクトリプロパティを、現アプリケーションディレクトリを指し示すように設定することと、ファイルのシャドウコピーを作成するよう指示することが重要です。シャドウコピーを作成することによって、アセンブリがアプリケーションディレクトリでロックされることを防止できます。ここで例外がスローされることはまずないと思われますが、それでも、何が起こったかをログに記録するためと、スレッドを例外で終わらせないために、例外を正確にキャッチするようにしました。アプリケーションにユーザインタフェースがないときは、こうやって例外をキャッチし、ログに記録することをお勧めします。