[Fixes #4525] Get rid of DNX services

This commit is contained in:
jacalvar 2016-04-27 12:44:29 -07:00
parent 4d198f3d8f
commit 059ec0f353
7 changed files with 1 additions and 486 deletions

17
Mvc.sln
View File

@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
VisualStudioVersion = 14.0.25123.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{DAAE4C74-D06F-4874-A166-33305D2643CE}"
EndProject
@ -143,8 +143,6 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "InlineConstraintSample.Web"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "MvcSubAreaSample.Web", "samples\MvcSubAreaSample.Web\MvcSubAreaSample.Web.xproj", "{45F6B3B6-D114-4D77-84D6-561B3957F341}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Mvc.Dnx", "src\Microsoft.AspNetCore.Mvc.Dnx\Microsoft.AspNetCore.Mvc.Dnx.xproj", "{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -868,18 +866,6 @@ Global
{45F6B3B6-D114-4D77-84D6-561B3957F341}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{45F6B3B6-D114-4D77-84D6-561B3957F341}.Release|x86.ActiveCfg = Release|Any CPU
{45F6B3B6-D114-4D77-84D6-561B3957F341}.Release|x86.Build.0 = Release|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Debug|x86.ActiveCfg = Debug|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Debug|x86.Build.0 = Debug|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Release|Any CPU.Build.0 = Release|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Release|x86.ActiveCfg = Release|Any CPU
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -950,6 +936,5 @@ Global
{396B40D7-AC70-49A7-B33C-ED42129FEBE3} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{EA34877F-1AC1-42B7-B4E6-15A093F40CAE} = {DAAE4C74-D06F-4874-A166-33305D2643CE}
{45F6B3B6-D114-4D77-84D6-561B3957F341} = {DAAE4C74-D06F-4874-A166-33305D2643CE}
{8FB691C2-DFD8-4FEE-9628-2BB8466A691C} = {32285FA4-6B46-4D6B-A840-2B13E4C8B58E}
EndGlobalSection
EndGlobal

View File

@ -1,88 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.PlatformAbstractions;
namespace Microsoft.AspNetCore.Mvc.Infrastructure
{
public class DnxAssemblyProvider
{
private readonly ILibraryManager _libraryManager;
public DnxAssemblyProvider(ILibraryManager libraryManager)
{
_libraryManager = libraryManager;
}
/// <summary>
/// Gets the set of assembly names that are used as root for discovery of
/// MVC controllers, view components and views.
/// </summary>
// DefaultControllerTypeProvider uses CandidateAssemblies to determine if the base type of a POCO controller
// lives in an assembly that references MVC. CandidateAssemblies excludes all assemblies from the
// ReferenceAssemblies set. Consequently adding WebApiCompatShim to this set would cause the ApiController to
// fail this test.
protected virtual HashSet<string> ReferenceAssemblies { get; } = new HashSet<string>(StringComparer.Ordinal)
{
"Microsoft.AspNetCore.Mvc",
"Microsoft.AspNetCore.Mvc.Abstractions",
"Microsoft.AspNetCore.Mvc.ApiExplorer",
"Microsoft.AspNetCore.Mvc.Core",
"Microsoft.AspNetCore.Mvc.Cors",
"Microsoft.AspNetCore.Mvc.DataAnnotations",
"Microsoft.AspNetCore.Mvc.Formatters.Json",
"Microsoft.AspNetCore.Mvc.Formatters.Xml",
"Microsoft.AspNetCore.Mvc.Localization",
"Microsoft.AspNetCore.Mvc.Razor",
"Microsoft.AspNetCore.Mvc.Razor.Host",
"Microsoft.AspNetCore.Mvc.TagHelpers",
"Microsoft.AspNetCore.Mvc.ViewFeatures"
};
/// <inheritdoc />
public IEnumerable<Assembly> CandidateAssemblies
{
get
{
return GetCandidateLibraries().SelectMany(l => l.Assemblies)
.Select(Load);
}
}
/// <summary>
/// Returns a list of libraries that references the assemblies in <see cref="ReferenceAssemblies"/>.
/// By default it returns all assemblies that reference any of the primary MVC assemblies
/// while ignoring MVC assemblies.
/// </summary>
/// <returns>A set of <see cref="Library"/>.</returns>
protected virtual IEnumerable<Library> GetCandidateLibraries()
{
if (ReferenceAssemblies == null)
{
return Enumerable.Empty<Library>();
}
// GetReferencingLibraries returns the transitive closure of referencing assemblies
// for a given assembly.
return ReferenceAssemblies.SelectMany(_libraryManager.GetReferencingLibraries)
.Distinct()
.Where(IsCandidateLibrary);
}
private static Assembly Load(AssemblyName assemblyName)
{
return Assembly.Load(assemblyName);
}
private bool IsCandidateLibrary(Library library)
{
Debug.Assert(ReferenceAssemblies != null);
return !ReferenceAssemblies.Contains(library.Name);
}
}
}

View File

@ -1,262 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
#if NETSTANDARD1_5
using System.Runtime.Loader;
#endif
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Dnx.Compilation.CSharp;
using Microsoft.Extensions.CompilationAbstractions;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Mvc.Razor.Internal
{
/// <summary>
/// A type that uses Roslyn to compile C# content and <see cref="ILibraryExporter"/> to find out references.
/// </summary>
public class DnxRoslynCompilationService : ICompilationService
{
private readonly ConcurrentDictionary<string, AssemblyMetadata> _metadataFileCache =
new ConcurrentDictionary<string, AssemblyMetadata>(StringComparer.OrdinalIgnoreCase);
private readonly IHostingEnvironment _environment;
private readonly ILibraryExporter _libraryExporter;
private readonly RazorViewEngineOptions _options;
private readonly Lazy<List<MetadataReference>> _applicationReferences;
#if NETSTANDARD1_5
private readonly RazorLoadContext _razorLoadContext;
#endif
/// <summary>
/// Initalizes a new instance of the <see cref="DnxRoslynCompilationService"/> class.
/// </summary>
/// <param name="environment">The environment for the executing application.</param>
/// <param name="libraryExporter">The library manager that provides export and reference information.</param>
/// <param name="optionsAccessor">Accessor to <see cref="RazorViewEngineOptions"/>.</param>
/// <param name="fileProviderAccessor">The <see cref="IRazorViewEngineFileProviderAccessor"/>.</param>
public DnxRoslynCompilationService(
IHostingEnvironment environment,
ILibraryExporter libraryExporter,
IOptions<RazorViewEngineOptions> optionsAccessor,
IRazorViewEngineFileProviderAccessor fileProviderAccessor)
{
_environment = environment;
_libraryExporter = libraryExporter;
_options = optionsAccessor.Value;
_applicationReferences = new Lazy<List<MetadataReference>>(GetApplicationReferences);
#if NETSTANDARD1_5
_razorLoadContext = new RazorLoadContext();
#endif
}
public CompilationResult Compile(RelativeFileInfo fileInfo, string compilationContent)
{
var assemblyName = Path.GetRandomFileName();
var sourceText = SourceText.From(compilationContent, Encoding.UTF8);
var syntaxTree = CSharpSyntaxTree.ParseText(
sourceText,
path: assemblyName,
options: _options.ParseOptions);
var references = _applicationReferences.Value;
var compilation = CSharpCompilation.Create(
assemblyName,
options: _options.CompilationOptions,
syntaxTrees: new[] { syntaxTree },
references: references);
using (var ms = new MemoryStream())
{
using (var pdb = new MemoryStream())
{
var result = compilation.Emit(ms);
if (!result.Success)
{
return GetCompilationFailedResult(
fileInfo.RelativePath,
compilationContent,
assemblyName,
result.Diagnostics);
}
ms.Seek(0, SeekOrigin.Begin);
var assembly = LoadStream(ms, assemblySymbols: null);
var type = assembly
.GetExportedTypes()[0];
return new CompilationResult(type);
}
}
}
internal CompilationResult GetCompilationFailedResult(
string relativePath,
string compilationContent,
string assemblyName,
IEnumerable<Diagnostic> diagnostics)
{
var diagnosticGroups = diagnostics
.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)
.GroupBy(diagnostic => diagnostic.Location.GetMappedLineSpan().Path, StringComparer.Ordinal);
var failures = new List<Diagnostics.CompilationFailure>();
foreach (var group in diagnosticGroups)
{
var sourceFilePath = group.Key;
var compilationFailure = new Diagnostics.CompilationFailure(
sourceFilePath,
string.Empty,
compilationContent,
group.Select(GetDiagnosticMessage));
failures.Add(compilationFailure);
}
return new CompilationResult(failures);
}
private static Diagnostics.DiagnosticMessage GetDiagnosticMessage(Diagnostic diagnostic)
{
var mappedLineSpan = diagnostic.Location.GetMappedLineSpan();
return new Diagnostics.DiagnosticMessage(
diagnostic.GetMessage(),
CSharpDiagnosticFormatter.Instance.Format(diagnostic),
mappedLineSpan.Path,
mappedLineSpan.StartLinePosition.Line + 1,
mappedLineSpan.StartLinePosition.Character + 1,
mappedLineSpan.EndLinePosition.Line + 1,
mappedLineSpan.EndLinePosition.Character + 1);
}
private Assembly LoadStream(MemoryStream ms, MemoryStream assemblySymbols)
{
#if NETSTANDARD1_5
return _razorLoadContext.Load(ms, assemblySymbols);
#else
return Assembly.Load(ms.ToArray(), assemblySymbols?.ToArray());
#endif
}
private List<MetadataReference> GetApplicationReferences()
{
var references = new List<MetadataReference>();
// Get the MetadataReference for the executing application. If it's a Roslyn reference,
// we can copy the references created when compiling the application to the Razor page being compiled.
// This avoids performing expensive calls to MetadataReference.CreateFromImage.
var libraryExport = _libraryExporter.GetExport(_environment.ApplicationName);
if (libraryExport?.MetadataReferences != null && libraryExport.MetadataReferences.Count > 0)
{
Debug.Assert(libraryExport.MetadataReferences.Count == 1,
"Expected 1 MetadataReferences, found " + libraryExport.MetadataReferences.Count);
var roslynReference = libraryExport.MetadataReferences[0] as IRoslynMetadataReference;
var compilationReference = roslynReference?.MetadataReference as CompilationReference;
if (compilationReference != null)
{
references.AddRange(compilationReference.Compilation.References);
references.Add(roslynReference.MetadataReference);
return references;
}
}
var export = _libraryExporter.GetAllExports(_environment.ApplicationName);
if (export != null)
{
foreach (var metadataReference in export.MetadataReferences)
{
// Taken from https://github.com/aspnet/KRuntime/blob/757ba9bfdf80bd6277e715d6375969a7f44370ee/src/...
// Microsoft.Extensions.Runtime.Roslyn/RoslynCompiler.cs#L164
// We don't want to take a dependency on the Roslyn bit directly since it pulls in more dependencies
// than the view engine needs (Microsoft.Extensions.Runtime) for example
references.Add(ConvertMetadataReference(metadataReference));
}
}
return references;
}
private MetadataReference ConvertMetadataReference(IMetadataReference metadataReference)
{
var roslynReference = metadataReference as IRoslynMetadataReference;
if (roslynReference != null)
{
return roslynReference.MetadataReference;
}
var embeddedReference = metadataReference as IMetadataEmbeddedReference;
if (embeddedReference != null)
{
return MetadataReference.CreateFromImage(embeddedReference.Contents);
}
var fileMetadataReference = metadataReference as IMetadataFileReference;
if (fileMetadataReference != null)
{
return CreateMetadataFileReference(fileMetadataReference.Path);
}
var projectReference = metadataReference as IMetadataProjectReference;
if (projectReference != null)
{
using (var ms = new MemoryStream())
{
projectReference.EmitReferenceAssembly(ms);
return MetadataReference.CreateFromImage(ms.ToArray());
}
}
throw new NotSupportedException();
}
private MetadataReference CreateMetadataFileReference(string path)
{
var metadata = _metadataFileCache.GetOrAdd(path, _ =>
{
using (var stream = File.OpenRead(path))
{
var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata);
return AssemblyMetadata.Create(moduleMetadata);
}
});
return metadata.GetReference(filePath: path);
}
#if NETSTANDARD1_5
private class RazorLoadContext : AssemblyLoadContext
{
protected override Assembly Load(AssemblyName assemblyName)
{
return Default.LoadFromAssemblyName(assemblyName);
}
public Assembly Load(Stream assembly, Stream assemblySymbols)
{
return LoadFromStream(assembly, assemblySymbols);
}
}
#endif
}
}

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>8fb691c2-dfd8-4fee-9628-2bb8466a691c</ProjectGuid>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\artifacts\bin\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -1,61 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
using Microsoft.AspNetCore.Mvc.Razor.Internal;
using Microsoft.Extensions.CompilationAbstractions;
using Microsoft.Extensions.PlatformAbstractions;
namespace Microsoft.Extensions.DependencyInjection
{
public static class MvcDnxServiceCollectionExtensions
{
/// <summary>
/// Adds services required for Mvc applications to work with DNX to the specified <paramref name="services"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" />.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IServiceCollection AddMvcDnx(this IServiceCollection services)
{
if (DnxPlatformServices.Default.LibraryManager != null)
{
var partManager = GetApplicationPartManager(services);
var provider = new DnxAssemblyProvider(DnxPlatformServices.Default.LibraryManager);
foreach (var assembly in provider.CandidateAssemblies)
{
partManager.ApplicationParts.Add(new AssemblyPart(assembly));
}
// Add IAssemblyProvider services
services.AddSingleton(DnxPlatformServices.Default.LibraryManager);
// Add compilation services
services.AddSingleton(CompilationServices.Default.LibraryExporter);
services.AddSingleton<ICompilationService, DnxRoslynCompilationService>();
}
return services;
}
private static ApplicationPartManager GetApplicationPartManager(IServiceCollection services)
{
var manager = GetServiceFromCollection<ApplicationPartManager>(services);
if (manager == null)
{
manager = new ApplicationPartManager();
}
return manager;
}
private static T GetServiceFromCollection<T>(IServiceCollection services)
{
return (T)services
.FirstOrDefault(d => d.ServiceType == typeof(T))
?.ImplementationInstance;
}
}
}

View File

@ -1,12 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: NeutralResourcesLanguage("en-us")]
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyProduct("Microsoft ASP.NET Core")]

View File

@ -1,30 +0,0 @@
{
"description": "Bridge for keeping compat with DNX.",
"version": "1.0.0-*",
"repository": {
"type": "git",
"url": "git://github.com/aspnet/mvc"
},
"compilationOptions": {
"warningsAsErrors": true,
"keyFile": "../../tools/Key.snk",
"nowarn": [ "CS1591" ],
"xmlDoc": true
},
"dependencies": {
"Microsoft.AspNetCore.Mvc.Razor": "1.0.0-*",
"Microsoft.Dnx.Compilation.CSharp.Common": "1.0.0-*",
"Microsoft.Dnx.Compilation.CSharp.Abstractions": "1.0.0-*",
"Microsoft.Extensions.DependencyInjection": "1.0.0-*",
"Microsoft.Extensions.PlatformAbstractions.Dnx": "1.0.0-*"
},
"frameworks": {
"net451": {},
"netstandard1.5": {
"imports": [
"portable-net451+win8",
"dotnet5.6"
]
}
}
}