问题描述
如何在MSBuild的自定义任务中访问当前项目上下文?最初,似乎 ProjectCollection 上的GlobalProjectCollection参考将允许访问,但这似乎是空的,至少在从命令行运行MSBuild时如此.
How do I access current Project context within a custom Task in MSBuild? At first it appeared as though the GlobalProjectCollection reference on ProjectCollection would allow access, but this appears to be empty, at least when running MSBuild from the commandline.
我目前可以通过以下方式从当前项目文件中获取新的Project实例:
I can currently get new Project instance based off of the current project file in the following manner:
List projectAssemblies = new List();
using (XmlReader projectFileReader =
XmlReader.Create(this.BuildEngine.ProjectFileOfTaskNode))
{
Project project = new Project(projectFileReader);
foreach (ProjectItem item in project.AllEvaluatedItems)
{
... woo hoo ...
}
}
但这似乎很麻烦.我如何才能访问从中调用任务的项目?
but it just seems like a lot of trouble. How can I just get access to the project from which my task is invoked?
推荐答案
您不能. MSBuild是经过专门设计的,因此单个任务只能访问您显式传递给任务的参数,而不能访问其他参数.现在,您知道每个任务仅受调用该任务时指定的内容的影响,这使MSBuild文件更易于阅读.
You can not. MSBuild was specifically designed so that individual tasks only have access to the parameters that you explicitly passed to the task, and nothing else. That makes MSBuild files easier to read, now that you know that each task is only affected by what your specidied when you called this task.
您拥有的代码不是创建项目的副本,而是创建新的实例,因此您不应期望属性相同.例如,当前执行项目的一个实例(从中调用您的任务的实例)的属性可以从命令行覆盖,也可以在构建项目的过程中进行更改,而新创建的项目在第一次执行后将具有该属性的默认值MSBuild引擎通过该文件.
The code you have is not creating a copy of the project, it is creating a new instance, so you should not expect properties to be the same. For example an instance of the currently executing project (from where your task is called from) could have properties overriden from command line or changed along the way your project is built, while your newly created project would have a default values of the properties after first MSBuild engine pass through the file.
这篇关于如何在自定义任务中访问当前项目上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!