2017-09-16 58 views
1

当下面的代码在MSBuild中运行时,我得到一个InvalidOperationException。我想知道为什么这是?为什么我不能在自定义任务构造函数中使用MsBuild TaskLoggingHelper?

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. 

回答

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任务。任务(您直接派生)做这在它的构造函数:

protected Task() 
{ 
    _log = new TaskLoggingHelper(this); 
} 
在这一点上_taskInstance.BuildEngine

所以仍然是空;它必须设置为elewhere。如何以及为什么基本上超出了这个答案的范围,因为它没有帮助你:你不能登录构造函数,并且没有任何可以改变的地方。

+0

感谢您的解释。你能解释一下怎样和为什么?我知道它不能帮助我,但我更感兴趣。再次感谢。 –

+0

我现在不是真的为什么这样做,因为它没有在代码中分解,但一个可能的原因是,构造函数保持简单,因此您可以编写无参数的构造函数而不必麻烦传递参数到基类构造函数,而其余的代码负责设置BuildEngine而不必关心它。在这里完成:https://github.com/Microsoft/msbuild/blob/master/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs#L369 – stijn

相关问题