PositiveGuy
PositiveGuy

Reputation: 47743

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>

Upvotes: 5

Views: 5650

Answers (3)

nethero
nethero

Reputation: 756

You have typo in your code

Constants.ignatureMethod, Constants.SignatureMethodTypeHMACSHA1}

It's should be

Constants.SignatureMethod, Constants.SignatureMethodTypeHMACSHA1}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726629

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.

Upvotes: 6

Andrew Barber
Andrew Barber

Reputation: 40150

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.

Upvotes: 2

Related Questions