Workaround for type initializer throwing exception

Source: Internet
Author: User

Today, when debugging the code, suddenly throws the following exception: "Xorm. Database "type initializer throws an exception.

Suddenly feel very abrupt, ordinary time a little problem did not, why today debugging on the issue? Tested and found an error in a instantiation code at the data processing layer:

            // Get mapping information            for a type Mappinginfo mapInfo = xmlmapping.getdatamapinfo (type);              new   Database ();//error code             = storageprocedure            ; // Get mapping information for a query condition

Looking for a long time did not find the reason, and then search the next online, is due to static member initialization exception caused by the problem. There is only one static member in my database class. The database class is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Data.SqlClient;usingSystem.Data;usingSystem.Collections;usingSystem.Configuration;namespacexorm{Internal classdatabase:idisposable { private static string _connectionstring = system.configuration.configurationmanager.connectionstrings["testforcssconn" ]. connectionstring;//Static memberPrivateIDbConnection _connection =NULL; Private string_commandtext =NULL; PrivateArrayList _parameters =NewArrayList (); Private BOOL_disposed;  PublicIDataReader Getdatareader () {using(IDbCommand cmd =GetCommand ()) {                returncmd.            ExecuteReader (); }        }        PrivateArrayList _inoutparameters =NewArrayList (); PrivateIDbCommand GetCommand () {IDbCommand cmd=connection.            CreateCommand (); Cmd.commandtext=_commandtext; Cmd.commandtype=CommandType.StoredProcedure; foreach(SqlParameter parminch_parameters) {cmd.            Parameters.Add (Parm); }            //parameters that can be entered and returned            foreach(SqlParameter parminch_inoutparameters) {Parm. Direction=ParameterDirection.Output; Cmd.            Parameters.Add (Parm); }            returncmd; }         PublicIDbCommand GetCommand () {returnGetCommand (); }         Public stringCommandText {Set{_commandtext =value;} Get{return_commandtext;} }        Privateidbconnection Connection {Get             {                if(_connection = =NULL) {_connection=NewSqlConnection (_connectionstring); _connection.                Open (); }                return_connection; }        }         Public voidAddParameters (stringNameObjectobj) {            if(name. StartsWith ("@") ==false) {Name="@"+name; } SqlParameter P=NewSqlParameter (name, obj); _parameters.        ADD (P); }         Public voidAddinoutparameters (stringNameObjectobj) {            if(name. StartsWith ("@") ==false) {Name="@"+name; } SqlParameter P=NewSqlParameter (name, obj);        _inoutparameters.add (P); }         PublicArrayList Parameters {Get{return_parameters;} }         Public voidDispose () {if(_disposed = =true)            {                return; }            //Dispose and close the connectionClose (); //This object is cleaned up by the Dispose method. //Therefore, you should the call GC. Supressfinalize to//Take this object off the finalization queue//and prevent finalization code for this object//From executing a second time.Gc. SuppressFinalize ( This); _disposed=true; }         Public voidClose () {if(_disposed = =true)            {                return; }            if(_connection! =NULL) {_connection.                Close (); _connection.            Dispose (); }        }    }}

After a careful comparison, I found that this statement is a problem, in my web. config configuration file, the database connection string is not named Testforcssconn, because the Web. config file is modified today, the new database connection fields are as follows:

<add name="testforcss" connectionstring="server= (local);D atabase= Bookexchange; User Id=sa; password=123; Connection timeout=180"          providerName="System.Data.SqlClient "/>

Modify the Name= "Testforcss" here to Name= "Testforcssconn".

Summarize the possible causes by searching online:

1. Accesses a static member of a class, while an exception is generated in the initialization (or static constructor) of other static members. For example, access to classhelper.staticstring, because the initialization of a static member field produces an exception, so calling Classhelper.staticstring throws TypeInitializationException.

2. Accesses a static member of a class that produces an exception in the initialization (or static constructor) of the static member.

3. Initialize the class, and an exception is generated in a static member initialization (or static constructor) in the class.

Workaround:

1. Check the static fields or properties in the class to ensure that they are properly initialized

2. In the constructor of the class, ensure that the property or field to which it is accessed has been initialized

3, if it is WinForm, the statement of the form control to be accessed is written after the initialization method

At the same time, the resulting error may also be an imported reference Sqlite.dll, the following is the workaround for this situation (refer to the Friend Snow Court):

Sqlite.dll 32-bit and 64-bit, formerly used in 32-bit, developed to win 7/x64 under. In the project properties, modify the platform, from any CPU to x86, re-run normal, Sqlite.dll is 32-bit, but the target platform is x64, about sqlite static variable initialization exception, cause the SQLite class initialization error, raised TypeInitializationException exception.

Workaround for type initializer throwing exception

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.