简体   繁体   中英

Type Initializer

I've got a config class:

namespace SomeCompanyName.SomeAppName
{
    public static class MyConfigClass
    {
        public static readonly string ConsKey = Config.GetAppConfigSetting("ConsKey");
        public static readonly string ConsSecret = Config.GetAppConfigSetting("ConsSecret");
     }
}

I've got a method trying to use some of these values in a dictionary:

public HttpWebResponse SomeMethod(....)
{

    Dictionary<string, string> headerParams = new Dictionary<string, string> {
        {Constants.Cons, MyConfigClass.ConsumerKey},
        {Constants.Token, MyConfigClass.SingleAccessToken},
        {Constants.ignatureMethod, Constants.SignatureMethodTypeHMACSHA1},
        {Constants.Timestamp, HttpUtility.GenerateTimeStamp()
    };
}

For some reason I'm getting this error:

"The type initializer for 'SomeAppConfig' threw an exception."

Can't figure out why if the SomeAppConfig class is static.

UPDATE:

Here's the definition of GetAppConfigSetting:

public class Config
{
    public static string GetAppConfigSetting(string configKey)
    {
        return ConfigurationManager.AppSettings[configKey] ?? string.Empty;
    }
}

UPDATE:

Here's the app.config in my Test project

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="ConsKey" value="HHGRT6jV4M" />
    <add key="ConsSecret" value="QR47dbduycAc" />
  </appSettings>

</configuration>

The type initializer of a static class is the code that sets the values of its static variables. In your case, it is this code:

public static readonly string ConsKey = Config.GetAppConfigSetting("ConsKey");
public static readonly string ConsSecret = Config.GetAppConfigSetting("ConsSecret");

Make sure that GetAppConfigSetting can access ConsKey and ConsSecret without a problem. The exception thrown from the initializer should have more information to help you debug the issue.

That means there was an exception in the static constructor. In this case, your property initializers. Perhaps the config keys you seek don't exist.

You have typo in your code

Constants.ignatureMethod, Constants.SignatureMethodTypeHMACSHA1}

It's should be

Constants.SignatureMethod, Constants.SignatureMethodTypeHMACSHA1}

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