简体   繁体   English

“MyClass”的类型初始值设定项引发异常

[英]The type initializer for 'MyClass' threw an exception

The following is my Windows service code.以下是我的 Windows 服务代码。 When I am debugging the code, I am getting the error/ exception:当我调试代码时,我收到错误/异常:

The type initializer for 'CSMessageUtility.CSDetails' threw an exception. “CSMessageUtility.CSDetails”的类型初始值设定项引发异常。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using CSMessageUtility;

namespace CS_Data_Trasmmiting_Service
{
    public partial class svcCSWinServ : ServiceBase
    {
        //private string sLogFormat;
        //private string sErrorTime;
        private Thread new_thread;
        Logger logObject = new Logger();
        private bool isenable = true;

        public svcCSWinServ()
        {
            InitializeComponent();
            logObject.append("Initialize Service " + DateTime.Now.ToString(), 70);
            CheckForAlarms();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                new_thread = new Thread(new ThreadStart(CheckForAlarms));
                new_thread.Start();
            }
            catch
            {
            }

            logObject.append("Service Started successfully " + DateTime.Now.ToString(), 70);
        }

        protected override void OnStop()
        {
            try
            {
                isenable = false;
                new_thread.Abort();
            }
            catch
            {

            }
            logObject.append("Service Stopped successfully " + DateTime.Now.ToString(), 70);
        }


        void CheckForAlarms()
        {
            try
            {
                while (true)
                {
                    //if((DateTime.Now.ToString("HH:mm") == "18:00"))
                    //{

                        logObject.append("Start Sending Data " +DateTime.Now.ToString(), 70);
                        try
                        {
                            //SendAllInfo();
                            string str = CSMessageUtility.CSDetails.createDHSMessageFormat();
                            Thread.Sleep(2000);
                            string str1 = CSMessageUtility.CSDetails.createEALMessageFormat();
                            Thread.Sleep(2000);
                            string str2 = CSMessageUtility.CSDetails.createProductStatusMessageForamt();
                            Thread.Sleep(2000);
                            string str3 = CSMessageUtility.CSDetails.createEODMessageFormat();
                            Thread.Sleep(2000);
                            string str4 = CSDetails.createProductReceiptEntryatBOSMessageFormat();
                            Thread.Sleep(2000);
                            string str5 = CSMessageUtility.CSDetails.createProductSaleMessageFormat();
                            Thread.Sleep(2000);
                            string str6 = CSMessageUtility.CSDetails.createTotalizerExceptionMessageFormat();
                            Thread.Sleep(2000);
                            //CSMessageUtility.CSDetails.createDailyCOtransferMessageFormat();
                            //Thread.Sleep(2000);

                        }
                        catch (Exception ee)
                        {
                            logObject.append(ee.Message, 70);
                        }
                        logObject.append("Finished Sending Data " +DateTime.Now.ToString(), 70);
                        Thread.Sleep(3000);
                    //}
                    //Thread.Sleep(20000);
                }
            }
            catch (Exception ex)
            {
                logObject.append("Thread Exception: "+ ex.Message + " "+ DateTime.Now.ToString(), 70);

                try
                {
                    new_thread.Abort();
                }
                catch (Exception ex1)
                {
                    logObject.append("Thread Exception: " +ex1.Message + " " + DateTime.Now.ToString(), 70);
                }

                if (isenable == true)
                {
                    new_thread = new Thread(new ThreadStart(CheckForAlarms));
                    new_thread.Start();
                }
            }
        }
    }
}

Check the InnerException property of the TypeInitializationException ;检查TypeInitializationExceptionInnerException属性; it is likely to contain information about the underlying problem, and exactly where it occurred.它可能包含有关潜在问题的信息,以及问题发生的确切位置。

This problem can be caused if a class tries to get value of a key in web.config or app.config which is not present there.如果类尝试获取web.configapp.config中不存在的键的值,则可能会导致此问题。

eg例如
The class has a static variable该类有一个静态变量

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

But the web.config doesn't contain the GoogleCalendarApplicationClientID keyweb.config不包含GoogleCalendarApplicationClientID

The error will be thrown on any static function call or any class instance creation该错误将在任何静态函数调用任何类实例创建时抛出

The type initializer for 'CSMessageUtility.CSDetails' threw an exception. means that the static constructor on that class threw an Exception - so you need to look either in the static constructor of the CSDetails class, or in the initialisation of any static members of that class.意味着该类上的静态构造函数抛出了一个异常 - 因此您需要查看 CSDetails 类的静态构造函数,或该类的任何静态成员的初始化。

I ran into the same problem, when I was using a static methods in a Util class, just like you had used CSMessageUtility.CSDetails .我遇到了同样的问题,当我在 Util 类中使用静态方法时,就像您使用CSMessageUtility.CSDetails

The problem was that during the static initialization of the class (using the static constructor), the framework also initialize the the static variables (fields) in the class.问题是在类的静态初始化期间(使用静态构造函数),框架还初始化了类中的静态变量(字段)。 I had a static variable that attempts to read values from app.config , and app.config was missing the respective settings, thus resulting in an un-handled exception.我有一个静态变量试图从app.config读取值,而app.config缺少相应的设置,从而导致未处理的异常。 This resulted in getting the这导致获得

"Object reference not set to an instance of an object." “你调用的对象是空的。”

as the inner exception.作为内部例外。

One other thing to check when these initialize errors are thrown would be to check if the target .NET version is installed on the server.检查何时抛出这些初始化错误的另一件事是检查目标 .NET 版本是否安装在服务器上。 You can right click the project and see what .NET version the application is targeting.您可以右键单击该项目并查看该应用程序面向的 .NET 版本。

由于有两个相同的配置属性(与 app.config 匹配),我遇到了同样的问题:

[ConfigurationProperty("TransferTimeValidity")]

This can happen if you have a dependency property that is registered to the wrong owner type (ownerType argument).如果您的依赖属性注册到错误的所有者类型(ownerType 参数),就会发生这种情况。

Notice SomeOtherControl should have been YourControl .注意SomeOtherControl应该是YourControl

public partial class YourControl
{
    public bool Enabled
    {
        get { return (bool)GetValue(EnabledProperty);   }
        set { SetValue(EnabledProperty, value); }
    }
    public static readonly DependencyProperty EnabledProperty =
        DependencyProperty.Register(nameof(Enabled), typeof(bool), typeof(SomeOtherControl), new PropertyMetadata(false));
}

Another scenario that might cause this is when you have a piece of your code that calls:另一种可能导致这种情况的情况是当您有一段代码调用:

string sParam = **ConfigurationManager.AppSettings["SOME_PARAM"].ToString();

Keep in mind that you have to use the OWSTIMER.EXE.CONFIG file for configuration file settings.请记住,您必须使用OWSTIMER.EXE.CONFIG文件进行配置文件设置。 I had an App.config file that I was trying to read and I was getting this error because on instantiation of my job instance, I had a line in my code that was referring to Connfiguration.AppSettings & Configuration.ConnectionStrings .我有一个App.config文件,我试图读取它,但我收到此错误,因为在实例化我的作业实例时,我的代码中有一行指的是Connfiguration.AppSettings & Configuration.ConnectionStrings Just make sure that you go the path:只要确保你走这条路:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

and place your configuration settings in the OWSTIMER.EXE.CONFIG file.并将您的配置设置放在OWSTIMER.EXE.CONFIG文件中。

Dictionary keys should be unique !字典键应该是唯一的!

In my case, I was using a Dictionary, and I found two items in it have accidentally the same key.就我而言,我使用的是字典,我发现其中的两个项目意外具有相同的键。

Dictionary<string, string> myDictionary = new Dictionary<string, string>() {
            {"KEY1", "V1"},
            {"KEY1", "V2" },
            {"KEY3", "V3"},
        };

If for whatever reason the power goes or the Visual Studio IDE crashes it can cause this problem inside your bin/debug bin/release...如果由于某种原因电源中断或 Visual Studio IDE 崩溃,它可能会在您的 bin/debug bin/release 中导致此问题...

Just delete the content and recompile (from personal experience when my toe hit the reset button!)只需删除内容并重新编译(根据我的脚趾按下重置按钮时的个人经验!)

I had a different but still related configuration.我有一个不同但仍然相关的配置。

Could be a custom configuration section that hasn't been declared in configSections .可能是尚未在configSections 中声明的自定义配置部分。

Just declare the section and the error should resolve itself.只需声明该部分,错误就会自行解决。

I encountered this issue due to mismatch between the runtime versions of the assemblies.由于程序集的运行时版本不匹配,我遇到了这个问题。 Please verify the runtime versions of the main assembly (calling application) and the referred assembly请验证主程序集(调用应用程序)和引用程序集的运行时版本

As the Error says the initialization of the Type/Class failed.由于错误说类型/类的初始化失败。 This usually occurs when there is some exception in the constructor of the class.这通常发生在类的构造函数中出现异常时。 Most common reason is you assign some value in the constructor reading from a config file and the config file is missing those values.最常见的原因是您在从配置文件读取的构造函数中分配了一些值,而配置文件缺少这些值。

In my case I had this failing on Logger.Create inside a class library that was being used by my main (console) app.在我的情况下,我在我的主(控制台)应用程序使用的类库中的 Logger.Create 上失败了。 The problem was I had forgotten to add a reference to NLog.dll in my console app.问题是我忘记在控制台应用程序中添加对 NLog.dll 的引用。 Adding the reference with the correct .NET Framework library version fixed the problem.添加具有正确 .NET Framework 库版本的引用解决了该问题。

Had a case like this in a WPF project.在 WPF 项目中有这样的案例。 My issue was on a line that went like this:我的问题是这样的:

DataTable myTable = FillTable(strMySqlQuery);

Where FillTable() returned a DataTable based on a SQL query string.其中FillTable()返回一个基于 SQL 查询字符串的 DataTable。 If I did the "copy exception to clipboard" option, I think it was, and pasted into Notepad, I could see the message.如果我做了“将例外复制到剪贴板”选项,我认为它是,并粘贴到记事本中,我可以看到消息。 For me, it was The input is not a valid Base-64 string as it contains a non-base 64 character .对我来说,它是The input is not a valid Base-64 string as it contains a non-base 64 character

My actual problem wasn't that the query string had something that shouldn't be there, like I was thinking, because string strMySqlQuery = "SELECT * FROM My_Table" was my string and thought it could be the * or _ , but the actual problem was in FillTable() , where I had a call to another function, GetConnection() that returned an OracleConnection object, in order to open it and retrieve and return the DataTable.我的实际问题不是查询字符串有一些不应该存在的东西,就像我在想的那样,因为string strMySqlQuery = "SELECT * FROM My_Table"是我的字符串,并认为它可能是*_ ,但实际问题出在FillTable() ,我在其中调用了另一个函数GetConnection() ,该函数返回了一个OracleConnection对象,以便打开它并检索并返回 DataTable。 Inside GetConnection() I was getting the app.config parameters for my connection string, and I had one of them misnamed, so it was setting a null value for the service account's password and not making the DB connection.GetConnection()我正在获取连接字符串的app.config参数,并且其中一个参数命名错误,因此它为服务帐户的密码设置了一个空值,而不是建立数据库连接。 So it's not always where the error is exactly correct for all circumstances.因此,对于所有情况,错误并不总是完全正确。 Best to dive into the function where the error is and debug step-by-step and ensure all values are getting filled with what you expect.最好深入了解错误所在的函数并逐步调试,并确保所有值都符合您的期望。

I too faced this error in two situation我在两种情况下也面临这个错误

  1. While performing redirection from BAL layer to DAL layer I faced this exception.在执行从 BAL 层到 DAL 层的重定向时,我遇到了这个异常。 Inner exception says that "Object Reference error".内部异常表示“对象引用错误”。

  2. Web.Config file key does not match. Web.Config文件键不匹配。

Hope this useful to solve your problem.希望这对解决您的问题有用。

Similar to what Muhammad Iqbal stated.. I was in a VB.NET (may also be C#) project where I did remove a key-value pair from the App.config which was referenced by a variable global to the Sub Main() of Module Main .类似于 Muhammad Iqbal 所说的......我在一个 VB.NET(也可能是 C#)项目中,我确实从App.config删除了一个键值对,它被一个全局变量引用到Sub Main() Module Main Therefore, the exception (and break) occurs in Module Main before the Sub Main() .因此,异常(和中断)发生在Sub Main()之前的Module Main If only I had a break-point on the Dim , but we don't usually break on global variables.如果我在Dim上有一个断点Dim ,但我们通常不会在全局变量上中断。 Perhaps a good reason not to declare globals referencing App.config?也许一个很好的理由不声明引用 App.config 的全局变量? In other words, this...换句话说,这...

An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module.未知模块中发生类型为“System.TypeInitializationException”的未处理异常。 The type initializer for 'Namespace.Main' threw an exception. “Namespace.Main”的类型初始值设定项引发异常。

Is caused by...是由...

App.config应用配置

<connectionStrings>
    <!--<add name="ConnectionString1" connectionString="..." />-->

Main module主模块

Module Main
    Dim cnnString As String = ConfigurationManager.ConnectionStrings("ConnectionString1")  '<-- BREAK HERE (EXCEPTION)

    Sub Main()

        // main code

    End Main
End Module

In my case, I had a helper class that was static.就我而言,我有一个静态的帮助类。 In that class was a method to initialize a SqlCommand dependent on variables.在那个类中有一个方法来初始化依赖于变量的 SqlCommand。 As this was being called in several places I moved it to the helper class and called as needed, so this method was also static.由于它在几个地方被调用,我将它移到了辅助类并根据需要调用,所以这个方法也是静态的。 Now I had a global property that was the connection string in Global.asax pointing to the connection string in web.config.现在我有一个全局属性,它是 Global.asax 中的连接字符串,指向 web.config 中的连接字符串。 Intermittently I would get "The type initializer for 'Helper' threw an exception".间歇性地我会得到“'Helper' 的类型初始值设定项抛出异常”。 If I moved the method from the Helper class to the class where it was being called from all was good.如果我将方法从 Helper 类移到从所有调用它的类中,那很好。 The inner exception complained of the object being null (Helper class).内部异常抱怨对象为空(Helper 类)。 What I did was add Using Helper to Global.asax and even though it was not being used by Global.asax this solved the problem.我所做的是将 Using Helper 添加到 Global.asax 中,即使 Global.asax 没有使用它,这也解决了问题。

My Answer is also related to Config section.我的回答也与配置部分有关。 If you assign values from Config file at static class of C# or Module.VB of VB, you will get this error at run time.如果您从 C# 的静态类或 VB 的 Module.VB 的 Config 文件中分配值,您将在运行时收到此错误。

add key="LogPath" value="~/Error_Log/"添加 key="LogPath" value="~/Error_Log/"

Using Forward slash in Web.Config also leads to this error on Run time.在 Web.Config 中使用正斜杠也会导致运行时出现此错误。 I just resolved this issue by putting BackSlash我刚刚通过放置 BackSlash 解决了这个问题

add key="LogPath" value="~\\Error_Log\\"添加 key="LogPath" value="~\\Error_Log\\"

I wrapped my line that was crashing in a try-catch block, printed out the exception, and breaked immediately after it was printed.我将崩溃的行包在 try-catch 块中,打印出异常,并在打印后立即中断。 The exception information shown had a stack trace which pointed me to the file and line of code causing the fault to occur.显示的异常信息有一个堆栈跟踪,它将我指向导致错误发生的文件和代码行。

在此处输入图片说明

System.TypeInitializationException: The type initializer for 'Blah.blah.blah' threw an exception. 
---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Some.Faulty.Software..cctor() in C:\Projects\My.Faulty.File.cs:line 56
   --- End of inner exception stack trace ---
   at Blah.blah.blah(Blah.blah.blah)
   at TestApplication.Program.Main(String[] args) 
   in C:\Projects\Blah.blah.blah\Program.cs:line 29 Exception caught.

以某种方式退出 Visual Studio 并重新打开它为我解决了这个问题。

Noteworthy: I had multiple projects in my solution and I forgot to add the references/Nuget libraries.值得注意的是:我的解决方案中有多个项目,但我忘记添加引用/Nuget 库。 When I ran a method in the static class, which used the given libraries, it threw the exception mentioned.当我在静态类中运行一个使用给定库的方法时,它抛出了提到的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM