【问题标题】:"Cannot find compilation library location for package "enc.dll"" error occur .net core dependency injection“找不到包“enc.dll”的编译库位置”错误发生.net核心依赖注入
【发布时间】:2018-04-20 14:33:35
【问题描述】:

我正在使用 asp.net core mvc 构建一个网站,对于登录,我添加了 enc.dll 文件的依赖项,它只是加密/解密用户信息。 我用 enc.dll 文件制作了一个 Seeder 类,它有一个 key 属性并用这个 key 加密/解密。然后我将它添加到我的服务中以使用依赖注入功能。

services.AddSingleton<ISeeder, Seeder>();

虽然当我调用播种器类的 enc、dec 函数时它运行良好,但它不会返回任何错误。下面是示例代码。

    private readonly ISeeder seed;
    public AccountController(ISeeder seed)
    {
        this.seed = seed;
    }

    [HttpGet]
    public IActionResult test()
    {
        string s = seed.Enc("testEncode");
        return Json(s);
    }

所以当我返回由种子实例创建的字符串 s 时它可以工作。

但是当我尝试在不使用种子实例的情况下返回视图并引发错误时它不起作用,其中 Enc 是我正在使用的 dll 库。

InvalidOperationException: Cannot find compilation library location for package 'Enc'
Microsoft.Extensions.DependencyModel.CompilationLibrary.ResolveReferencePaths(ICompilationAssemblyResolver resolver, List<string> assemblies)

下面是我的播种机代码。

 private Enc enc;
    private readonly EncKey key;
    public Seeder(IOptions<EncKey> options)
    {
        enc = new Enc();
        key = options.Value;
    }

    public string Dec(string toDec)
    {
        return enc.Dec(toDec, key.EncryptKey);
    }

    public string Enc(string toEnc)
    {
        return enc.Enc(toEnc, key.EncryptKey);
    }

有人可以帮忙吗?我正在开发 .net core 2.0 环境

【问题讨论】:

  • 这个问题在2.0.3已经修复,应用需要通过nuget更新VS和项目包
  • @itikhomi 谢谢,现在可以使用了。

标签: c# dependency-injection asp.net-core-mvc asp.net-core-2.0


【解决方案1】:

更新

此问题在 2.0.3 中已修复,应用需要更新 VS(或手动 dotnet SDK 和运行时)和通过 nuget 的项目包(特别是 Microsoft.AspNetCore.All 到 2.0.3)

.Net Core 2.0 的已知问题https://github.com/dotnet/core-setup/issues/2981

Razor 视图预编译无法解析 lib 路径

这里解决方法来完成这项工作:

添加这个(它正在修复发布发布错误)

using Microsoft.AspNetCore.Mvc;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.DependencyModel.Resolution;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace somenamespace
{
    public class MvcConfiguration : IDesignTimeMvcBuilderConfiguration
    {
        private class DirectReferenceAssemblyResolver : ICompilationAssemblyResolver
        {
            public bool TryResolveAssemblyPaths(CompilationLibrary library, List<string> assemblies)
            {
                if (!string.Equals(library.Type, "reference", StringComparison.OrdinalIgnoreCase))
                {
                    return false;
                }

                var paths = new List<string>();

                foreach (var assembly in library.Assemblies)
                {
                    var path = Path.Combine(ApplicationEnvironment.ApplicationBasePath, assembly);

                    if (!File.Exists(path))
                    {
                        return false;
                    }

                    paths.Add(path);
                }

                assemblies.AddRange(paths);

                return true;
            }
        }

        public void ConfigureMvc(IMvcBuilder builder)
        {
            // .NET Core SDK v1 does not pick up reference assemblies so
            // they have to be added for Razor manually. Resolved for
            // SDK v2 by https://github.com/dotnet/sdk/pull/876 OR SO WE THOUGHT
            /*builder.AddRazorOptions(razor =>
            {
                razor.AdditionalCompilationReferences.Add(
                    MetadataReference.CreateFromFile(
                        typeof(PdfHttpHandler).Assembly.Location));
            });*/

            // .NET Core SDK v2 does not resolve reference assemblies' paths
            // at all, so we have to hack around with reflection
            typeof(CompilationLibrary)
                .GetTypeInfo()
                .GetDeclaredField("<DefaultResolver>k__BackingField")
                .SetValue(null, new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[]
                {
                    new DirectReferenceAssemblyResolver(),
                    new AppBaseCompilationAssemblyResolver(),
                    new ReferenceAssemblyPathResolver(),
                    new PackageCompilationAssemblyResolver(),
                }));
        }
    }
}

还有这个(它正在修复编译错误)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyModel;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;

namespace somenamespace
{
    public class ReferencesMetadataReferenceFeatureProvider : IApplicationFeatureProvider<MetadataReferenceFeature>
    {
        public void PopulateFeature(IEnumerable<ApplicationPart> parts, MetadataReferenceFeature feature)
        {
            var libraryPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            foreach (var assemblyPart in parts.OfType<AssemblyPart>())
            {
                var dependencyContext = DependencyContext.Load(assemblyPart.Assembly);
                if (dependencyContext != null)
                {
                    foreach (var library in dependencyContext.CompileLibraries)
                    {
                        if (string.Equals("reference", library.Type, StringComparison.OrdinalIgnoreCase))
                        {
                            foreach (var libraryAssembly in library.Assemblies)
                            {
                                libraryPaths.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, libraryAssembly));
                            }
                        }
                        else
                        {
                            foreach (var path in library.ResolveReferencePaths())
                            {
                                libraryPaths.Add(path);
                            }
                        }
                    }
                }
                else
                {
                    libraryPaths.Add(assemblyPart.Assembly.Location);
                }
            }

            foreach (var path in libraryPaths)
            {
                feature.MetadataReferences.Add(CreateMetadataReference(path));
            }
        }

        private static MetadataReference CreateMetadataReference(string path)
        {
            using (var stream = File.OpenRead(path))
            {
                var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata);
                var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata);

                return assemblyMetadata.GetReference(filePath: path);
            }
        }
    }
}

还将 addMVC 更改为此

//workaround https://github.com/dotnet/core-setup/issues/2981 will be fixed in 2.0.1
            services.AddMvc().ConfigureApplicationPartManager(manager =>
            {
                var oldMetadataReferenceFeatureProvider = manager.FeatureProviders.First(f => f is MetadataReferenceFeatureProvider);
                manager.FeatureProviders.Remove(oldMetadataReferenceFeatureProvider);
                manager.FeatureProviders.Add(new ReferencesMetadataReferenceFeatureProvider());
            });

你将能够在你的视图中使用 dll

您还有第二种方法是在此处禁用剃须刀预编译示例 Deleting PrecompiledViews.dll from ASP.Net Core 2 API

【讨论】:

  • 感谢它有效,尽管新的“MvcConfiguration”类似乎没有必要。我阅读了这篇文章,应用了解决方案,我的确实可以在没有“MvcConfiguration”类的情况下工作
  • @ringord,尝试发布没有“MvcConfiguration”类的版本,在我的情况下,我总是在发布时遇到错误
  • 你的意思是它可以在没有 MvcConfiguration 类的本地环境中工作,但它不能在服务器中?
  • @ringord,尝试在您的项目中创建发布文件夹配置文件,然后尝试在没有 MvcConfiguration 的情况下发布到文件夹,您将收到错误 Error The command ""dotnet" exec --runtimeconfig "\bin\Release \netcoreapp2.0\XXX.runtimeconfig.json" --depsfile "\bin\Release\netcoreapp2.0\XXX.deps.json" "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.razor .viewcompilation\2.0.0\build\netstandard2.0\Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.dll" @"obj\Release\netcoreapp2.0\microsoft.aspnetcore.mvc.razor.viewcompilation.rsp"" 退出代码 1.
  • @ringord,我的意思是如果没有 MvcConfiguration,MvcRazorCompileOnPublish 将无法工作
猜你喜欢
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
  • 2019-02-16
  • 1970-01-01
  • 2018-01-03
  • 2021-03-02
  • 1970-01-01
相关资源
最近更新 更多