2017-09-16 59 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

相關問題