【问题标题】:Application Settings in custom class ASP.Net 5 MVC 6自定义类 ASP.Net 5 MVC 6 中的应用程序设置
【发布时间】:2016-09-11 04:49:45
【问题描述】:

使用 ASP.Net 5 MVC。看到这个问题跳来跳去,但不是一个完整的答案。我想要做的是有一个能够访问 AppSettings 的助手类。我可以在控制器和视图中访问它,但还没有弄清楚如何在我自己的自定义类中访问它。像这样配置启动。

public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.

        var builder = new ConfigurationBuilder()
            .AddJsonFile("config.json")
            .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddOptions();
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    }
.................
.................

【问题讨论】:

    标签: c# asp.net asp.net-core-mvc


    【解决方案1】:

    所以在你的 config.json 文件中,假设你有以下设置

    {
        "smtp": {
            "SenderEmail": "a@b.com",
            "SenderFrom": "Test User"
        }
    }
    

    然后在您的 ConfigureServices 方法中,您需要执行类似的操作

    services.Configure&lt;SmtpEmailSetting&gt;(Configuration.GetSection("smtp"));

    这是你的 SmtpEmailSetting 的样子

    public class SmtpEmailSetting
    {
        public string SenderEmail { get; set; }
        public string SenderFrom { get; set; }
    }
    

    这是您在任何服务或控制器中访问设置的方式

    public class SendEmailService
    {
        private readonly SmtpEmailSetting _smtpEmailSetting;
    
        public SendEmailService(IOptions<SmtpEmailSetting> smtpOptions )
        {
            _smtpEmailSetting = smtpOptions.Value;
        }
    
        public void SendEmail()
        {
            var fromEmail = _smtpEmailSetting.SenderEmail;
            var displayName = _smtpEmailSetting.SenderFrom;
        }
    }
    

    所以基本上你使用你的设置或选项(无论你喜欢调用什么)应该在构造函数中用作IOptions&lt;&gt;类的泛型类型参数。希望对你有帮助

    【讨论】:

      【解决方案2】:

      为了在您的自定义类中访问您的 AppSettings 属性,请将配置设置为静态实例,例如:

      public static IConfigurationRoot Configuration { get; set; }
      

      并在应用程序中的任何位置使用您的 AppSettings(例如连接字符串):

      var connectionString = Startup.Configuration["Data:DefaultConnection:ConnectionString"];
      

      【讨论】:

        【解决方案3】:

        只是为了添加到 adeel41 的答案,这是正确的并且效果很好,但对我自己来说,我不想在使用依赖注入时拖动 IOption 对象。

        所以我更喜欢做类似的事情

        services.AddSingleton<ISmtpEmailSettings>(Configuration.GetSection("SmtpSettings").Get<SmtpEmailSettings>());
        

        最重要的是添加到 GetSection 的 Get 语法以将您的 JSON 反序列化为对象。

        【讨论】:

          【解决方案4】:

          在 RC1 的时候,我从 Rick Strahl 的 this post 中获得灵感,效果很好。这与已经提出的其他方法非常相似。

          这个答案只是为了更新我在 RTM 发布时的发现。 Configuration.GetSection(string topLevelKey) 似乎不再起作用了,至少对我来说它总是返回 null(即使配置源设置正确)。

          经过一番搜索,this other SO thread 指出了正确的方向,使用:

          // create empty config object
          var smtpEmailSetting = new SmtpEmailSetting();
          
          // fill it from configuration section
          Configuration.GetSection("smtp").Bind(smtpEmailSetting);
          
          // use it, e.g. by registering it into DI
          services.Configure<SmtpEmailSetting>(smtpEmailSetting);
          

          HTH

          【讨论】:

            【解决方案5】:

            如果您在自己的类中需要它,将它传递给该类的构造函数或作为参数可能是正确的。例如;

            public class Notifications
            {
                public Notifications(AppSettings settings) {
                    this.settings = settings;
                }
            
                public void SendEmail(string subject, string body) {
                    SmptClient.Send(subject, body, settings["email address"]);
                }
            }
            

            因此,通常情况下,您会从控制器传递它。

            这避免了全局变量,我认为这总是一件好事。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-09-11
              • 1970-01-01
              • 1970-01-01
              • 2021-09-13
              • 1970-01-01
              • 2015-06-12
              相关资源
              最近更新 更多