简体   繁体   中英

App wide Static Variable C# Console application

I am looking to use a variable Config instantiated in Program.cs to be able to use in other classes I have. As I understand, we need to use dependency injection, but not sure how to achieve.


Program.cs

public class Program
{
    static IConfigurationRoot Config = null;

    public static void Main(string[] args)
    {
        Config = new ConfigurationBuilder()
          .SetBasePath(Environment.CurrentDirectory)
          .AddJsonFile("appsettings.json")
          .AddEnvironmentVariables()
          .Build();
    }
}

TestClass.cs

public class TestClass
{
    public void DoSomething()
    {
         // Now I need to use that instantiated Config object here.
    }
}

You can either make Config static public , so it can be accessed anywhere in your application, or, if you want to use Dependency Injection, make your TestClass constructor ask for one IConfigurationRoot :

public TestClass(IConfigurationRoot config) 
{
    // do what you need
    // save a reference to it on a local member, for example
}

Now every time you instantiate a new TestClass , you will have to pass by argument to its constructor the IConfigurationRoot object it will use. If that proves to be troublesome (eg: you instantiate TestClass a lot, in a lot of different places), then you might use a TestClassFactory :

public class TestClassFactory
{
    public TestClass Get()
    {
        // Do your logic here to get a new TestClass object
        // The IConfigurationRoot object that will be used to create TestClasses
        // will be chosen here.
    }
}

Also, if you don't want to use ASP.NET types directly, you may, as Crowcoder pointed out, make a config repository, as you would do for any database model. That repository would fetch configuration from a json file, for example.

Something like this:

public class ConfigurationRepository : IConfigurationRepository
{
    public string GetBasePath()
    {
        // Read base path from config files
    }

    public string SetBasePath()
    {
        // Write base path to config files
    }
}

And then you would use DI to pass IConfigurationRepository to your TestClass .

如果Config声明为public static ,则可以从其他类作为Program.Config对其进行访问Program.Config

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM