'How to declare global variable in Program cs and use it in controllers in .NET 6.0 Web Api

I have default Program.cs file from Web Api template in .NET 6.0. I am adding variable "test" so I can use its value in controllers.

var builder = WebApplication.CreateBuilder(args);
const string test = "test123";
builder.Configuration.Bind(test);

//rest of the file...

And now I want to use variable "test" outside Program.cs but I have no idea how to do it. I cannot just simply use it because when trying to read it in controller like this:

string localVar = test;

I am getting an error "'test' is not null here. Cannot use local variable or local function declared in a top-level statement in this context". This is probably some stupid mistake but I can't figure it out...



Solution 1:[1]

Starting C# 9, we don't need to explicitly mention the Main method in Program.cs file as we can use the top-level statements feature. However, it doesn't mean that we shouldn't use the default Program class in the created file at all. In your case, you have a need to define the static/const property so you can change the newly created structure into the old one.

namespace WebApplication;

public class Program
{
    public static string Test { get; private set; }
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        Program.Test = "approach1";
        builder.Services.Configure<MyOptions>(x => x.Test = "approach2");
        ///
}

public class MyOptions
{
    public string Test { get; set; }
}

I assumed that you have a need to set the value to the Program.Test field during runtime, so in the first approach, I used the static field with a private set; accessor instead of the constant.

In the second approach, I used the C# options feature to configure the MyOptions.Test field value, this will be very flexible and useful to write unit tests later. But, you need to inject the MyOptions class wherever is required.

In the below controller template, I specified how to access the configured values at Program.cs file, inside the Get method

public class TestController : ControllerBase
{
    private readonly MyOptions _myOptions;

    public TestController (IOptions<MyOptions> myOptions)
    {
        _myOptions = myOptions.Value;
    }

    public IActionResult Get()
    {
        string test1 = Program.Test;
        string test2 = _myOptions.Test;
        ///
    }

}

Solution 2:[2]

Add public partial class Program { } at the very end of your Program.cs file and add constant, property or whatever you like in there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Fernell85