【问题标题】:App wide Static Variable C# Console application应用范围的静态变量 C# 控制台应用程序
【发布时间】:2017-01-15 04:22:52
【问题描述】:

我希望使用在Program.cs 中实例化的变量Config 以便能够在我拥有的其他类中使用。据我了解,我们需要使用依赖注入,但不知道如何实现。


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.
    }
}

【问题讨论】:

  • 在另一个类中引用可执行程序集的成员是不寻常的。我认为你应该重新考虑设计。
  • 您能建议如何做到这一点吗?我的要求是能够在应用程序的任何位置访问所有配置条目。
  • 我喜欢创建配置存储库并将配置数据视为任何数据存储(如数据库)。因此,也许可以专门创建一个类来保存这些字段。如果该变量通过 Program.Config 公开,您可以使用该变量,但就 SOLID 原则而言,这将是对 Program 类的滥用。

标签: c# .net dependency-injection console-application .net-core


【解决方案1】:

您可以创建 Config static public,以便可以在您的应用程序中的任何位置访问它,或者,如果您想使用依赖注入,请让您的 TestClass 构造函数请求一个 IConfigurationRoot

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

现在每次实例化一个新的TestClass 时,您都必须通过参数将其将使用的IConfigurationRoot 对象传递给它的构造函数。如果这被证明很麻烦(例如:您在很多不同的地方实例化了很多 TestClass),那么您可以使用 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.
    }
}

此外,如果您不想直接使用 ASP.NET 类型,您可以像 Crowcoder 指出的那样创建一个配置存储库,就像对任何数据库模型所做的那样。例如,该存储库将从 json 文件中获取配置。

类似这样的:

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

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

然后您将使用 DI 将 IConfigurationRepository 传递给您的 TestClass

【讨论】:

    【解决方案2】:

    如果Config 被声明为public static,那么它可以作为Program.Config 被其他类访问

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-13
      • 2016-12-28
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      相关资源
      最近更新 更多