本文介绍了如何在 dotnet 构建任务中访问包引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在使用 dotnet build 运行的 Microsoft Build Task 中使用 Microsoft.CodeAnalysis 等包引用?

Is it possible to use package references like Microsoft.CodeAnalysis within a Microsoft Build Task running with dotnet build?

我使用 netstandard1.5 作为任务库和以下包引用:

I'm using netstandard1.5 for the task library and the following package references:

<PackageReference Include="Microsoft.Build" Version="15.3.0-preview-000117-01" />
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="15.3.0-preview-000117-01" />
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="2.2.0" />

消费项目是一个netcoreapp1.1.任务失败并显示

The consuming project is a netcoreapp1.1. The task fails with an

MyTask"任务意外失败.System.IO.FileNotFoundException:无法加载文件或程序集Microsoft.CodeAnalysis,版本=2.2.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35"或其依赖项之一.该系统找不到指定的文件.文件名:'Microsoft.CodeAnalysis,版本=2.2.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35'

例外.

当尝试通过 AssemblyLoadContext.Default.LoadFromAssemblyPath 加载包引用时,我得到

When trying to load the package reference via AssemblyLoadContext.Default.LoadFromAssemblyPath I get

无法加载文件或程序集Microsoft.CodeAnalysis,版本=2.2.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35".

没有任何附加信息.这在 .net 核心控制台应用程序中运行时也不起作用.我尝试了第二个(更简单的)包,它可以通过 LoadFromAssemblyPath 在 .net 核心控制台应用程序中加载,但在作为 dotnet build Task 运行时它仍然不起作用.

without any additional information. This does not work when running in a .net core console application either. I tried a second (simpler) package, which can be loaded via LoadFromAssemblyPath in a .net core console application, but still it does not work when running as dotnet build Task.

在控制台应用程序中使用 Assembly.LoadFile 在经典 net4.6 中运行时以及作为任务运行时,都可以加载这两个程序集.

Both assemblies can be loaded when running in classical net4.6 with Assembly.LoadFile in a console application and when running as Task though.

推荐答案

不幸的是,任务 dll 无法引用任何包 - 它们被加载到正在运行的 msbuild 实例中,并且只能引用托管 msbuild 实例可用的 dll.任何其他 DLL 都可以通过 .net 核心中的 AssemblyLoadContext 或 .net 框架中的 AppDomain.Load() 加载.没有对任务的 dll 文件进行依赖解析,这也意味着可能与已加载的 dll、msbuild 的不同部分或其他任务存在冲突.在 .NET Framework MSBuild 中,可以将任务隔离到自己的 AppDomains 中,但此机制在 .NET Core 上不可用.

Unfortunately task dlls cannot reference any packages - they are loaded into the running msbuild instance and will only be able to reference the dlls that are available to the hosting msbuild instance. Any other DLLs could be loaded via AssemblyLoadContext in .net core or AppDomain.Load() in .net framework. No dependency resolution is performed for the task's dll file, this also means that there may be conflicts with already loaded dlls, different parts of msbuild or other tasks. In .NET Framework MSBuild, tasks can be isolated to their own AppDomains, but this mechanism is not available on .NET Core.

这篇关于如何在 dotnet 构建任务中访问包引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 19:07