【问题标题】:Why the value are not reflecting in the service layer为什么价值没有反映在服务层
【发布时间】:2018-01-08 13:57:32
【问题描述】:

应用程序配置

 <appSettings>
  <add key="maxDiscount" value="25"/>
 </appSettings>  

这是我的 CustomerConfig.cs

    public class CustomerConfig
    {
    private static int GetValue(string key)
    {
        return Convert.ToInt16(ConfigurationManager.AppSettings[key]);
    }

    public static int MaxDiscount
    {
        get
        {
            return GetValue("maxDiscount");
        }
  }

服务类

 public class CustomerService : ICustomer
{
    private readonly int _maxDiscount;

    public CustomerService() 
    {
        //the value is NOT reflecting here
        _maxDiscount = CustomerConfig.MaxDiscount;
        //watching at this line I see _maxDiscount = 0
    }
}

注意:- 以上所有这些类都在同一层(类库项目) 而下面的控制器在另一个层(UI层)

MVC 控制器。

public class SomeController : Controller
{
 private readonly int _maxDiscount;
 public SomeController() 
        : base()
    {
        //here the value 25 is reflecting
         _maxDiscount = CustomerConfig.MaxDiscount;
    }
}

为什么 maxDiscount 的值没有反映在服务层??

是什么原因造成的?如何在服务层中获取值??

【问题讨论】:

  • value not reflecting 是什么意思?同一个项目的服务类和 CustomConfig 类的一部分? app.config 位于何处?是不是获取不到web.config中配置的值?
  • @ChetanRanpariya 服务类、CustomConfig 和 App.Config 都是同一个项目的一部分,而 SomeController 是另一个层(UI 层)

标签: c# asp.net asp.net-mvc static app-config


【解决方案1】:

ConfigurationManager 将从正在执行的程序集配置文件中加载配置。在您的场景中,它将是 web.config 文件。

如果你想让它工作,你应该在你的 web.config 文件中添加该设置,或者,你真的想这样做,你可以尝试使用 ConfigurationManager.OpenExeConfiguration Method 但我不知道这是否是个好主意(或如果它适用于 dll)。

【讨论】:

  • 是的。刚刚检查过,你的陈述似乎是真的。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 2018-09-03
  • 1970-01-01
  • 2016-10-03
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多