Reputation: 235
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?
Upvotes: 0
Views: 3636
Reputation: 218847
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;
}
}
}
Upvotes: 1