Steven Scott
Steven Scott

Reputation: 11250

C# Create Global instance of a Static Class

I have inherited a base of code, and I am looking to do a small change without a lot of refactoring for some static functions in a class to be able to use with configuration information.

My issue is that there is a static class that has functions for interacting with the console. These static functions can then simply be called using the Console.Write() notation. The problem I have is I need to put some configuration changes into the static class based on command line options passed to the main program.

While I would normally use Dependency Injection to support this, the code base does not have an instance of this class being passed to objects that use it. I need to configure a setting in the static class at runtime to control how the functions in the class work.

I am at a loss on how to do this with C# (and other languages) without doing the larger change to support dependency injection.

Short Sample of the static class access

public class ConsoleUtilities
{
    public static string ApplicationVersion
    {
        get
        {
            Assembly MyProgram = Assembly.GetEntryAssembly();
            return MyProgram.GetName().Version.ToString();
        }
    }

    /// <summary>
    /// Show Text on the screen, and optionally write to LogPathFileName
    /// </summary>
    /// <param name="HelpText">Text to show</param>
    /// <param name="LogPathFileName">Path and File Name of LogFile to write to. Use "" to not Log</param>
    public static void ShowText(string[] HelpText, string LogPathFileName)
    {
        foreach (string HelpLine in HelpText)
        {
            ShowText(HelpLine, System.ConsoleColor.Gray, System.ConsoleColor.Black, LogPathFileName);
        }
    }

    public static void ShowText(string HelpLine, System.ConsoleColor Foreground, System.ConsoleColor Background, string LogPathFileName)
    {
        ShowTextOnConsole(HelpLine, Foreground, Background, true, LogPathFileName);
    }
}

Sample Program using the static class

public class Program
{
    public enum EXIT_CODES { OK = 0, CONFIG_ERROR, FILE_ERROR, COMPARE_ERROR, EXECUTION_ERROR, WARNING };
    public const string LogPathFileName = "Tool.log";

    static int Main(string[] args)
    {
        int ApplicationExitCode = (int)EXIT_CODES.OK;
        int Failures = 0;

        string[] AboutText = { 
            "Tool.exe - " + CSharpUtilities.ConsoleUtilities.ApplicationVersion,
            "Copyright (c) 2014",
            ""
        };

        Settings AppSettings = new Settings(AboutText);

        // Ensure Command Line is valid before proceeding 
        ApplicationExitCode = (int)EXIT_CODES.CONFIG_ERROR;
        ApplicationCommandLine AppCommandLine = new ApplicationCommandLine();

        try
        {
            if (AppCommandLine.ParseCommandLine(args))
            {
                // Load Application Settings
                LoadApplicationSettings(ref AppSettings, AppCommandLine);
                ConsoleUtilities.ShowText(AboutText, LogPathFileName);
                List<string> ValidationErrors = ValidateApplicationSettings(AppSettings);
                if (ValidationErrors.Count == 0)
                {
                    ...
                }
                else
                {
                    ConsoleUtilities.ShowText(ValidationErrors.ToArray(), LogPathFileName);
                }
            }
        }

        catch (Exception e)
        {
            ApplicationExitCode = (int)EXIT_CODES.EXECUTION_ERROR;      // Exception occured in processing. Fail the program execution.
            string[] SystemError = { "System Error", e.Message.ToString() };
            ConsoleUtilities.ShowText(SystemError, LogPathFileName);
        }

    }
}

Upvotes: 1

Views: 353

Answers (2)

Xiaoy312
Xiaoy312

Reputation: 14477

You can expose the configuration as a static field or property :

public class ConsoleUtilities
{
    public static string ApplicationVersion
    {
        get
        {
            Assembly MyProgram = Assembly.GetEntryAssembly();
            return MyProgram.GetName().Version.ToString();
        }
    }

    public static ConsoleConfiguration Configuration = new ConsoleConfiguration();

    /// <summary>
    /// Show Text on the screen, and optionally write to LogPathFileName
    /// </summary>
    /// <param name="HelpText">Text to show</param>
    /// <param name="LogPathFileName">Path and File Name of LogFile to write to. Use "" to not Log</param>
    public static void ShowText(string[] HelpText, string LogPathFileName)
    {
        foreach (string HelpLine in HelpText)
        {
            ShowText(HelpLine, Configuration.BackgroundColor, Configuration.ForegroundColor, LogPathFileName);
        }
    }

    public static void ShowText(string HelpLine, System.ConsoleColor Foreground, System.ConsoleColor Background, string LogPathFileName)
    {
        ShowTextOnConsole(HelpLine, Foreground, Background, true, LogPathFileName);
    }
}

public class ConsoleConfiguration
{
    public ConsoleColor ForegroundColor { get; set; }
    public ConsoleColor BackgroundColor { get; set; }

    public ConsoleConfiguration()
    {
        ForegroundColor = ConsoleColor.Gray;
        BackgroundColor = ConsoleColor.Black;
    }
}

And you can reconfigurate like :

ConsoleUtilities.Configuration.ForegroundColor = ...

Upvotes: 1

Dmitri Soshnikov
Dmitri Soshnikov

Reputation: 727

You can put static fields in the static class, and initialize them in your program after parsing the command line. For example:

public class ConsoleUtilities
{
   public static bool ShowLog { get; set; } = true; // true, if we want log messages to be printed

   public static void Log(string[] HelpText, string LogPathFileName)
   {
    if (ShowLog) {
    foreach (string HelpLine in HelpText)
    {
        ShowText(HelpLine, System.ConsoleColor.Gray, System.ConsoleColor.Black, LogPathFileName);
    }
   }
}

}

And then when parsing command line somewhere in your code you would use

ConsoleUtilities.ShowLog = true; // or false

Upvotes: 4

Related Questions