简体   繁体   中英

Call a constant name from web.config

In a webserivce coding, I want to call a constant name from web.config. I have this code :

namespace Service.AppCode.Common.Service
{
    [ServiceContract(Namespace = Constants.Namespace)]
    public interface IService1
    {
        [OperationContract]
        void DoWork();
    }
}

and this code:

namespace Service.AppCode.Common
{
    public class Constants
    {
        public const string Namespace = ConfigurationManager.AppSettings["DefaulIP"];
    }
}

it will say :

The expression being assigned to 'Service.AppCode.Common.Constants.Namespace' must be constant

is it possible to call it from web.config?

Constants are defined at compile-time and embedded directly into the resulting code, they're not initialized when the application executes. (And can't change, unlike a config value which very much can change.)

However, looking at this...

public class Constants
{
    public readonly static string Namespace = 
        ConfigurationManager.AppSettings["DefaulIP"];
}

It looks like you just want a static immutable value. That's easy enough...

public class Constants
{
    public static string Namespace
    {
        get { return ConfigurationManager.AppSettings["DefaulIP"]; }
    }
}

That would read the value dynamically from the configuration any time it's invoked. And since it's only a getter, it's read-only. If you want it to only read from the config once, just cache the value:

public class Constants
{
    private static string _namespace = null;
    public static string Namespace
    {
        get
        {
            if (_namespace == null)
                _namespace = ConfigurationManager.AppSettings["DefaulIP"];
            return _namespace;
        }
    }
}

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