Home > OS >  System.TypeInitializationException when application initializes SQL connection
System.TypeInitializationException when application initializes SQL connection

Time:09-26

I have a ASP.NET MVC web application developed in .NET Framework 4.7.1. When I host the application in IIS different from source machine, I am getting the error System.TypeInitializationException. This error is only occurring when the application is trying to connect to the database, also the application and database connection is not established but the same publish is working in another server with the same specifications and configurations. All I am getting is the below error. enter image description here

I have tested if the assembly version is different on run time using the below method

 public void GetAssemblyInformation()
        {
            var names = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
            string path = @"D:\FilePath\AssemblyInfo.txt";
            System.IO.File.WriteAllLines(path, names.Select(i => i.ToString()).ToArray());
        }

but I found the same assembly versions found on both server and host machine, Can anybody help me what mistake I would have done here

CodePudding user response:

Without seeing more of the code, I'll give you my best guess.

First we need to understand what a TypeInitializationException means:

When a class initializer fails to initialize a type, a TypeInitializationException is created and passed a reference to the exception thrown by the type's class initializer. The InnerException property of TypeInitializationException holds the underlying exception.

So before we can fix it, we need to find the root cause of the problem, which we do by catching this exception so that we can see the (real) InnerException:

try {
    // code that we think is erroring (database connection or call maybe)    
}
catch (TypeInitializationException e) {
    throw e.InnerException;
}

Given the scenario you explain, there is a good chance that initializing the database connection class is failing and you aren't catching database connection errors. So start by putting the try/catch around that code. You should then be able to see and then fix that error.

To make your application more resilient in the future you might want to look at some defensive coding. Because, without seeing the code, I can't be sure - but it seems as though you are trying to consume the returned data and instead managing to consume the exception being thrown during the database call.

i.e. you have a via model expecting a SchoolManagement.Business.Masters.BIUsers object, which is tries to read blindly from the database call, and is instead getting the TypeInitializationException, which it is obviously unhappy about.

  • Related