前回 Webロール(osFamily=2) に Application Initialization Module for IIS 7.5 を組み込み半自動で動作するようなことを書きましたが、Application Initialization Module は IIS8 からはサーバーの機能として有効または無効にできる項目になっていますので、Webロールでも osFamily=3 であれば、もっと簡単に自動化を含めて機能を組み込むことが可能ですね。
では、その方法です。
対象のフレームワークを .NET Framework 4.5 などにした Webロールを含んだプロジェクトを作ります。
ServiceDefitition.csdef を開いて管理者権限に設定します。
<Runtime executionContext="elevated"></Runtime>
ServiceConfiguration.Cloud(Local).cscfgファイルの osFamily が 3 に設定されていることを確認します。
参照設定に %windir%\system32\inetsrv にある Microsoft.Web.Administration を追加します。
WebRole.cs を下記のように編集します。
public override bool OnStart() { // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. ExecuteCommand("cmd.exe", "\" /c dism /online /enable-feature /featurename:IIS-ApplicationInit\""); InitAppHostConfig(); return base.OnStart(); } private void ExecuteCommand(string exe, string arguments) { using (var p = new Process()) { p.StartInfo.FileName = exe; p.StartInfo.Arguments = arguments; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.Verb = "RunAs"; p.Start(); var results = p.StandardError.ReadToEnd(); p.WaitForExit(60000); p.Close(); } } private void InitAppHostConfig() { using (var serverManager = new ServerManager()) { var site = serverManager.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_Web"]; var app = site.Applications["/"]; app["preloadEnabled"] = true; var apppool = serverManager.ApplicationPools[app.ApplicationPoolName]; apppool["startMode"] = "AlwaysRunning"; serverManager.CommitChanges(); } }
プロジェクトのルートにある web.config の system.webServer に下記の設定を追加します。
以上で設定は終了ですので、デプロイします。
前回は msiファイル(appwarmup_x64.msi)をインストールしましたが、今回は dism コマンドで Application Initialization の機能を追加しています。また、インスタンスがあがったあとに、手動でなんやかんやする手順が無くなってるので、とっても簡単に自動化することが出来ますね。