[.net] Could not load type from assembly error

I have written the following simple test in trying to learn Castle Windsor's Fluent Interface:

using NUnit.Framework;
using Castle.Windsor;
using System.Collections;
using Castle.MicroKernel.Registration;

namespace WindsorSample {
    public class MyComponent : IMyComponent {
        public MyComponent(int start_at) {
            this.Value = start_at;
        }
        public int Value { get; private set; }
    } 
    public interface IMyComponent {
        int Value { get; }
    }

    [TestFixture]
    public class ConcreteImplFixture {
        [Test]
        public void ResolvingConcreteImplShouldInitialiseValue() {
            IWindsorContainer container = new WindsorContainer();
            container.Register(Component.For<IMyComponent>().ImplementedBy<MyComponent>().Parameters(Parameter.ForKey("start_at").Eq("1")));
            IMyComponent resolvedComp = container.Resolve<IMyComponent>();
            Assert.AreEqual(resolvedComp.Value, 1); 
        }
    }
}

When I execute the test through TestDriven.NET I get the following error:

System.TypeLoadException : Could not load type 'Castle.MicroKernel.Registration.IRegistration' from assembly 'Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'.
at WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue()

When I execute the test through the NUnit GUI I get:

WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue:
System.IO.FileNotFoundException : Could not load file or assembly 'Castle.Windsor, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc' or one of its dependencies. The system cannot find the file specified.

If I open the Assembly that I am referencing in Reflector I can see its information is:

Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc

and that it definitely contains Castle.MicroKernel.Registration.IRegistration

What could be going on?

I should mention that the binaries are taken from the latest build of Castle though I have never worked with nant so I didn't bother re-compiling from source and just took the files in the bin directory. I should also point out that my project compiles with no problem.

This question is related to .net

The answer is


I want to mention additional things and make a conclusion.

Commonly, As Otherones explained, This exception will raise when there is a problem with loading expected type (in an existing assembly) in runtime. More specific, Whenever there is loaded assembly that is stale (and not contains the requiring type). Or when an assembly with different version or build is already loaded that not contains the expected type.

Also, I must mention that It seems Rarely, But It is possible to be runtime limitation or a compiler bug (suppose compiler not negated about something and just compiled problematic code), But runtime throws System.TypeLoadException exception. Yes; this actually occurred for me!

An Example (witch occurred for me)

Consider an struct that defines a nullable field of its own type inside itself. Defining such the filed non-nullable, will take you a compile-time error and prevents you from build (Obviously This behavior has a logical reason). But what about nullable struct filed? Actually, nullable value-types is Nullable<T> at behind. As c# compiler not prevented me from defining in this way, I tried it and the project built. But I get runtime exception System.TypeLoadException: 'Could not load type 'SomeInfo' from assembly ... ', And It seems to be Problem in loading the part of my code (otherwise, we may say: the compiler not-truly performed compilation process at least) for me in my environment:

public struct SomeInfo
{
   public SomeInfo? Parent { get; } 
   
   public string info { get; }
}

My environment specs:

  • Visual Studio 2019 16.4.4
  • Language Version: c# 7.3
  • Project type: netstandard 2.0.3 library
  • Runtime: classic DotNetFramework 4.6.1

(I checked and ensured that the compiled assembly is up to date And actually is newly compiled. Even, I throwed away all bin directory and refreshed the whole project. Even I created a new project in a fresh solution and tested, But such the struct generates the exception.)

It seems to be a runtime limitation (logically or technically) or bug or a same problem else, because Visual Studio not prevents me from compile And Also other newer parts of my codes (excluding this struct) are executing fine. Changing the struct to a class, the compiled assembly contains and executes the type as well.

I have no any idea to explain in-detail why this behavior occurs in my environment, But I faced this situation.

Conclusion

Check the situations:

  • When a same (probably older) assembly already exists in GAC that is overriding the referenced assembly.

  • When re-compilation was need but not performed automatically (therefore the referenced assembly is not updated) and there is needs to perform build manually or fix solution build configuration.

  • When a custom tool or middleware or third-party executable (such as tests runner tool or IIS) loaded an older version of that assembly from cached things and there is need to cleaning somethings up or causing to reset somethings.

  • When an Unappropriated Configuration caused demanding a no longer existing type by a custom tool or middleware or a third-party executable that loads the assembly and there is need to update configuration or cleaning somethings up (such as removing an http handler in web.config file on IIS deployment as @Brian-Moeskau said)

  • When there is a logical or technical problem for runtime to execute the compiled assembly, (for example when compiler was compiled a problematic code that the in-using runtime cannot understand or execute it), as I faced.


Deleting my .pdb file for the dll solved this issue for me. I'm guessing it has something to do with the fact that the dll was created using ILMerge.


I was getting this error and nothing I found on StackOverflow or elsewhere solved it, but bmoeskau's answer to this question pointed me in the right direction for the fix, which hasn't been mentioned yet as an answer. My answer isn't strictly related to the original question, but I'm posting it here under the assumption that someone having this problem will find there way here through searching Google or something similar (like myself one month from now when this bites me again, arg!).

My assembly is in the GAC, so there is theoretically only one version of the assembly available. Except IIS is helpfully caching the old version and giving me this error. I had just changed, rebuilt and reinstalled the assembly in the GAC. One possible solution is to use Task Manager to kill w3wp.exe. This forces IIS to reread the assembly from the GAC: problem solved.


Maybe not as likely, but for me it was caused by my application trying to load a library with the same assembly name (xxx.exe loading xxx.dll).


You might be able to resolve this with binding redirects in *.config. http://blogs.msdn.com/b/dougste/archive/2006/09/05/741329.aspx has a good discussion around using older .net components in newer frameworks. http://msdn.microsoft.com/en-us/library/eftw1fys(vs.71).aspx


I had this issue after factoring a class name:
Could not load type 'Namspace.OldClassName' from assembly 'Assembly name...'.

Stopping IIS and deleting the contents in Temporary ASP.NET Files fixed it up for me.

Depeding on your project (32/64bit, .net version, etc) the correct Temporary ASP.NET Files differs:

  • 64 Bit
    %systemroot%\Microsoft.NET\Framework64\{.netversion}\Temporary ASP.NET Files\
  • 32 Bit
    %systemroot%\Microsoft.NET\Framework\{.netversion}\Temporary ASP.NET Files\
  • On my dev machine it was (Because its IIS Express maybe?)
    %temp%\Temporary ASP.NET Files

I get this occasionally and it's always been down to have the assembly in the GAC


Version=1.0.3.0 indicates Castle RC3, however the fluent interface was developed some months after the release of RC3. Therefore, it looks like you have a versioning problem. Maybe you have Castle RC3 registered in the GAC and it's using that one...


Adding your DLL to GAC(global assembly cache)

Visual Studio Command Prompt => Run as Adminstrator

gacutil /i "dll file path"

You can see added assembly C:\Windows\system32\

It Will also solve dll missing or "Could not load file or assembly" in SSIS Script task


I had the same issue. I just resolved this by updating the assembly via GAC.

To use gacutil on a development machine go to: Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010).

I used these commands to uninstall and Reinstall respectively.

gacutil /u myDLL

gacutil /i "C:\Program Files\Custom\mydllname.dll"

Note: i have not uninstall my dll in my case i have just updated dll with current path.


This usually happens when you have one version of your assembly deployed in the GAC but has not been updated with new classes that you might have added on the assembly on your IDE. Therefore make sure that the assembly on the GAC is updated with changes you might have made in your project.

E.g. if you have a Class Library of Common and in that Class Library you have Common.ClassA type and deploy this to the GAC strongly-named. You come later and add another type called Common.ClassB and you run your code on your IDE without first deploying the changes you made to the GAC of Common with the newly added Common.ClassB type.


If this error caused by changing the namespace, make sur that the folder of that project is renamed to the same name, and close VS.NET Edit the project which has the problem with Notepad and replace there nodes

"RootNamespace>New_Name_Of_Folder_Of_Your_Project_Namespace"RootNamespace> "AssemblyName>New_Name_Of_Folder_Of_Your_Project_Namespace"AssemblyName>


I ran into this scenario when trying to load a type (via reflection) in an assembly that was built against a different version of a reference common to the application where this error popped up.

As I'm sure the type is unchanged in both versions of the assembly I ended up creating a custom assembly resolver that maps the missing assembly to the one my application has already loaded. Simplest way is to add a static constructor to the program class like so:

using System.Reflection
static Program()
{
    AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => {
        AssemblyName requestedName = new AssemblyName(e.Name);

        if (requestedName.Name == "<AssemblyName>")
        {
            // Load assembly from startup path
            return Assembly.LoadFile($"{Application.StartupPath}\\<AssemblyName>.dll");
        }
        else
        {
            return null;
        }
    };
}

This of course assumes that the Assembly is located in the startup path of the application and can easily be adapted.


The solution to this for me was not mentioned above, so I thought I would add my answer to the long tail...

I ended up having an old reference to a class (an HttpHandler) in web.config that was no longer being used (and was no longer a valid reference). For some reason it was ignored while running in Studio (or maybe I have that class still accessible within my dev setup?) and so I only got this error once I tried deploying to IIS. I searched on the assembly name in web.config, removed the unused handler reference, then this error went away and everything works great. Hope this helps someone else.


If this is a Windows app, try checking for a duplicate in the Global Assembly Cache (GAC). Something is overriding your bin / debug version.

If this is a web app, you may need to delete on server and re-upload. If you are publishing you may want to check the Delete all existing files prior to publish check box. Depending on Visual Studio version it should be located in Publish > Settings > File Publish Options Delete all existing files prior to publish


I experienced the same as above after removing signing of assemblies in the solution. The projects would not build.

I found that one of the projects referenced the StrongNamer NuGet package, which modifies the build process and tries to sign non-signed Nuget packages.

After removing the StrongNamer package I was able to build the project again without signing/strong-naming the assemblies.


I had the same issue and for me it had nothing to do with namespace or project naming.

But as several users hinted at it had to do with an old assembly still being referenced.

I recommend to delete all "bin"/binary folders of all projects and to re-build the whole solution. This washed out any potentially outdated assemblies and after that MEF exported all my plugins without issue.


I got the same error after updating a referenced dll in a desktop executable project. The issue was as people here mentioned related an old reference and simple to fix but hasn’t been mentioned here, so I thought it might save other people’s time.

Anyway I updated dll A and got the error from another referenced dll let’s call it B here where dll A has a reference to dll B.

Updating dll B fixed the issue.


Just run into this with another cause:

running unit tests in release mode but the library being loaded was the debug mode version which had not been updated


When I run into such problem, I find FUSLOGVW tool very helpful. It is checking assembly binding information and logs it for you. Sometimes the libraries are missing, sometimes GAC has different versions that are being loaded. Sometimes the platform of referenced libraries is causing the problems. This tool makes it clear how the dependencies' bindings are being resolved and this may really help you to investigate/debug your problem.

Fusion Log Viewer / fuslogvw / Assembly Binding Log Viewer. Check more/download here: http://msdn.microsoft.com/en-us/library/e74a18c4.aspx.


If you have one project referencing another project (such as a 'Windows Application' type referencing a 'Class Library') and both have the same Assembly name, you'll get this error. You can either strongly name the referenced project or (even better) rename the assembly of the referencing project (under the 'Application' tab of project properties in VS).


Just run into this with another cause:

I was using a merged assembly created with ILRepack. The assembly you are querying the types from must be the first one passed to ILRepack or its types will not be available.


Yet another solution: Old DLLs pointing to each other and cached by Visual Studio in

C:\Users\[yourname]\AppData\Local\Microsoft\VisualStudio\10.0\ProjectAssemblies

Exit VS, delete everything in this folder and Bob's your uncle.


I experienced a similar issue in Visual Studio 2017 using MSTest as the testing framework. I was receiving System.TypeLoadException exceptions when running some (not all) unit tests, but those unit tests would pass when debugged. I ultimately did the following which solved the problem:

  1. Open the Local.testsettings file in the solution
  2. Go to the "Unit Test" settings
  3. Uncheck the "Use the Load Context for assemblies in the test directory." checkbox

After taking these steps all unit tests started passing when run.


I just resolved this by running the iisreset command using the command prompt... Always the first thing I do when I get such errors.