// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.Mvc.Razor.Precompilation;
using Microsoft.Framework.Caching.Memory;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Runtime;
using Microsoft.Framework.Runtime.Roslyn;
namespace Microsoft.AspNet.Mvc
{
///
/// An implementation that pre-compiles Razor views in the application.
///
public abstract class RazorPreCompileModule : ICompileModule
{
private readonly IServiceProvider _appServices;
private readonly IMemoryCache _memoryCache;
///
/// Instantiates a new instance.
///
/// The for the application.
public RazorPreCompileModule(IServiceProvider services)
{
_appServices = services;
// When ListenForMemoryPressure is true, the MemoryCache evicts items at every gen2 collection.
// In DTH, gen2 happens frequently enough to make it undesirable for caching precompilation results. We'll
// disable listening for memory pressure for the MemoryCache instance used by precompilation.
_memoryCache = new MemoryCache(new MemoryCacheOptions { ListenForMemoryPressure = false });
}
///
/// Gets or sets a value that determines if symbols (.pdb) file for the precompiled views is generated.
///
public bool GenerateSymbols { get; protected set; }
///
/// Pre-compiles all Razor views in the application.
public virtual void BeforeCompile(IBeforeCompileContext context)
{
var compilerOptionsProvider = _appServices.GetRequiredService();
var loadContextAccessor = _appServices.GetRequiredService();
var compilationSettings = GetCompilationSettings(compilerOptionsProvider, context.ProjectContext);
var fileProvider = new PhysicalFileProvider(context.ProjectContext.ProjectDirectory);
var viewCompiler = new RazorPreCompiler(
context,
loadContextAccessor,
fileProvider,
_memoryCache,
compilationSettings)
{
GenerateSymbols = GenerateSymbols
};
viewCompiler.CompileViews();
}
///
public void AfterCompile(IAfterCompileContext context)
{
}
private static CompilationSettings GetCompilationSettings(
ICompilerOptionsProvider compilerOptionsProvider,
IProjectContext projectContext)
{
return compilerOptionsProvider.GetCompilerOptions(projectContext.Name,
projectContext.TargetFramework,
projectContext.Configuration)
.ToCompilationSettings(projectContext.TargetFramework);
}
}
}