为什么我不能在自定义任务构造函数中使用MsBuild TaskLoggingHelper?

时间:2017-09-16 04:05:28

标签: logging msbuild

当在MSBuild中运行以下代码时,我得到一个InvalidOperationException。我想知道为什么会这样?

public class SimpleTask3 : Task
{
    public SimpleTask3()
    {
        Log.LogMessage(MessageImportance.High, "A MESSAGE");
    }


    public override bool Execute()
    {
        return true;
    }
}

收到的完整错误如下

error MSB4061: The "SimpleTask3" task could not be instantiated from ...ConsoleApplication1.dll
error MSB4061: System.InvalidOperationException: Task attempted to log before it was initialized. Message was: A MESSAGE
error MSB4061:    at Microsoft.Build.Shared.ErrorUtilities.ThrowInvalidOperation(String resourceName, Object[] args)
error MSB4061:    at Microsoft.Build.Utilities.TaskLoggingHelper.LogMessage(MessageImportance importance, String message, Object[] messageArgs)
error MSB4061:    at SimpleTask3.SimpleTask3..ctor() in SimpleTask.cs:line 10
error MSB4060: The "SimpleTask3" task hasbeen declared or used incorrectly, or failed during construction. Check the spelling of the task name and the assembly name.

1 个答案:

答案 0 :(得分:0)

TaskLoggingHelper实例通过BuildEngine.LogMessageEvent进行日志记录,因此它们需要BuildEngine实例才能使用它们。来自source code

// If BuildEngine is null, task attempted to log before it was set on it,
// presumably in its constructor. This is not allowed, and all
// we can do is throw.
if (BuildEngine == null)
{
  ErrorUtilities.ThrowInvalidOperation("LoggingBeforeTaskInitialization", e.Message);
}

BuildEngine属性转发到_taskInstance.BuildEngine,_taskInstance是创建TaskLoggingHelper的Task。一个Task(你直接从中派生)在它的构造函数中执行此操作:

protected Task()
{
  _log = new TaskLoggingHelper(this);
}

所以那时_taskInstance.BuildEngine仍为null;它必须设置在elewhere。如何以及为什么基本上超出了这个答案的范围,因为它对你没有帮助:你无法登录构造函数,也没有任何关于它的改变......

相关问题