MSBuild on .NET 5: Microsoft.Build.Utilities.Task not able to get singleton set in console application after converting to .NET 5 (works for .NET Framework)

kthage 1 Reputation point
2021-12-13T14:42:58.787+00:00

I'm having an issue using a singleton after converting a Microsoft.Build console project with a separate task library project from .NET Framework 4.7.2 to .NET 5.

With the .NET Framework version, I'm able to set the singleton in the console application and read the value in the build task (Microsoft.Build.Utilities.Task).

This will not work with .NET 5.

Any thoughts on this?

Console app (also containing the Context singleton)...

class Program
{
    static void Main(string[] args)
    {
        // Singleton to be used in the build task (visible in .NET Framework, but not on .NET 5)
        Context.Instance.Id = Guid.NewGuid();

        // Create project
        Microsoft.Build.Evaluation.ProjectCollection projectCollection = new Microsoft.Build.Evaluation.ProjectCollection();
        projectCollection.DefaultToolsVersion = "Current";

        Microsoft.Build.Evaluation.Project project = projectCollection.LoadProject(@".\TestProject.proj");

        // Return true if there is a value in the singleton Id, false if null.
        bool success = project.Build("Target");

        System.Diagnostics.Debug.WriteLine($"Context contains a value: {success}");
    }
}

In a library, this task is defined.
public class TestTask : Microsoft.Build.Utilities.Task
{
public override bool Execute()
{
return MsBuildTest.Context.Instance.Id != null;
}
}

Community Center | Not monitored
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

1 answer

Sort by: Most helpful
  1. Ken Tucker 5,861 Reputation points
    2021-12-14T01:44:21.907+00:00

    Remember .net 5 is cross platform. You will need to use a Mutex to make app single instance

     const string mutexName = @"Global\appName";
    
     var mutex = new Mutex(true, mutexName, out var createdNew);
    
     if (!createdNew)
     {
           Console.WriteLine(mutexName + " is already running! Exiting the application.");
           return;
     }
    

    Source https://stackoverflow.com/questions/47005542/single-instance-net-core-app-or-making-crontab-run-only-1-instance-of-my-app


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.