RazorEngine使用時に一時ファイルが残らないようにする
ソフトウェア開発担当のRyuです。
.NETでテンプレートエンジンが使いたくて検索したところ、RazorEngineが使いやすいということなので、利用してみました。
使い方などは他にも書いてる方がたくさん居るみたいなので、表題の一時ファイルを消す方法のみを書きます。
RazorEngineはテンプレートコンパイル時に一時ファイルを作成します。
アプリケーション終了時に消そうとするけど、デフォルトドメインで実行した場合、プロセスにファイルを掴まれててどうしても消せないときがある模様。
ということでこちらにその対処方法が記載されていました。
static int Main(string[] args)
{
if (AppDomain.CurrentDomain.IsDefaultAppDomain())
{
// RazorEngine cannot clean up from the default appdomain...
Console.WriteLine("Switching to secound AppDomain, for RazorEngine...");
AppDomainSetup adSetup = new AppDomainSetup();
adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
var current = AppDomain.CurrentDomain;
// You only need to add strongnames when your appdomain is not a full trust environment.
var strongNames = new StrongName[0];
var domain = AppDomain.CreateDomain(
"MyMainDomain", null,
current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
strongNames);
var exitCode = domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);
// RazorEngine will cleanup.
AppDomain.Unload(domain);
return exitCode;
}
// Continue with your code.
}
このコードをそのまま貼り付ければいいだけという、至れり尽くせりなサポートです。
ドメインの概念って今までほとんど意識してなかったんですけど、こんな風に使うんですね(勉強不足)。
また、どうしてもデフォルトドメインで動かしたい場合にも
- テンプレート数が限られている。
- 隔離の必要がない、信頼できるテンプレートしか使用しない。
- デバッグサポートの必要がない。
- 実行時にテンプレートを変更しない。
の条件に合致するなら、
var config = new TemplateServiceConfiguration();
config.DisableTempFileLocking = true; // loads the files in-memory (gives the templates full-trust permissions)
config.CachingProvider = new DefaultCachingProvider(t => {}); //disables the warnings
Engine.Razor = RazorEngineService.Create(config);
上記コードで対処してもいいようです。