Could not load type from assembly error

.Net

.Net Problem Overview


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.

.Net Solutions


Solution 1 - .Net

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).

Solution 2 - .Net

Is the assembly in the Global Assembly Cache (GAC) or any place the might be overriding the assembly that you think is being loaded? This is usually the result of an incorrect assembly being loaded, for me it means I usually have something in the GAC overriding the version I have in bin/Debug.

Solution 3 - .Net

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.

Solution 4 - .Net

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.

Solution 5 - .Net

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.

Solution 6 - .Net

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

Solution 7 - .Net

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>

Solution 8 - .Net

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.

Solution 9 - .Net

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...

Solution 10 - .Net

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

Solution 11 - .Net

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.

Solution 12 - .Net

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).

Solution 13 - .Net

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.

Solution 14 - .Net

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

Solution 15 - .Net

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.

Solution 16 - .Net

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.

Solution 17 - .Net

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.

Solution 18 - .Net

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.

Solution 19 - .Net

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

Solution 20 - .Net

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.

Solution 21 - .Net

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

Solution 22 - .Net

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.

Solution 23 - .Net

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.

Solution 24 - .Net

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

Solution 25 - .Net

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.

Solution 26 - .Net

Usually the dll is not found, or the dll exists, but the new class cannot be found.

  1. if the dll does not exist, update the dll directly

  2. If there is a dll, take it down and use ILSPY to see if there is a class in it that reports an error.

If not, rebuild the dll and upload it again.

Solution 27 - .Net

I tried most of the above, but none of them worked for me.

Here was my issue.

I moved a c# project from my local machine (Windows 10) to the server (Windows Server 2008 R2). I started getting the 'could not load assembly' error when trying to run tests from my UnitTest project.

Here is my solution.

I removed the test project from the solution which was a Unit Test Project .NET Framework. I also made sure to delete the project. I then created a new MSTest Test Project .NET Core project.

Solution 28 - .Net

I got this error when trying to load a Blazor component in a .NET 5 C# MVC solution that broke out the Blazor components into its own project in the solution:

enter image description here

My DTO objects are used for specifically for the Blazor stuff and has no ref to AspNetCore.Mvc stuff (as that breaks Blazor).

So strangely, when I try to load the component with just the object I need, like this (in the MVC View):

<component type="typeof(My.Client.Components.MyComponent)" render-mode="WebAssemblyPrerendered"
       param-OpenYearMonth="Model.OpenYearMonth?.ToDTO()" />

I get the same error as the OP in my browser console. However, for some strange reason, just adding an extra dummy parameter causes it to load just fine:

<component type="typeof(My.Client.Components.MyComponent)" render-mode="WebAssemblyPrerendered"
       param-Whatever="new List<My.DTO.Models.Whatever>()"
       param-OpenYearMonth="Model.OpenYearMonth?.ToDTO()" />

I think the problem is that the component is being rendered without the DTO assembly being loaded? Maybe? It doesn't make much sense and certainly seems like a bug in the MVC or Blazor... but I guess at least there is some work around. I also tried doing some Task.Delay experiments, thinking maybe the DTO assembly was still being loaded or something but that didn't help. I also tried creating a local variable in the View with this Model.OpenYearMonth?.ToDTO() and passing that local variable to the component... again no help. Of course I also tried all of the solutions in the answers of this post and none of that helped. Don't ask how many hours this issue wasted...

Solution 29 - .Net

Had a similar System.TypeLoadException : Could not load type 'referenced assembly'.'non-existing class'Extension.

I had added a new String extension to the referenced assembly, deployed it along with a second assembly which had also changed (and used the referenced assembly) to the web application bin folder.

Although the web application used the referenced assembly it did not use the new extension method. I understood I retained binary compatibility by not changing the assembly version (just the file version) of the referenced assembly and assumed it would be loaded by the web application assembly.

It appears that the web application assembly would still not load the newer file version of the referenced assembly from its bin folder.

To fix I simply recompiled the web application assembly and redeployed it.

Solution 30 - .Net

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorge MauerView Question on Stackoverflow
Solution 1 - .NetAndrewSView Answer on Stackoverflow
Solution 2 - .NetEric SchoonoverView Answer on Stackoverflow
Solution 3 - .NetBrian MoeskauView Answer on Stackoverflow
Solution 4 - .NetMattView Answer on Stackoverflow
Solution 5 - .NetMichael MaddoxView Answer on Stackoverflow
Solution 6 - .NetCJSewellView Answer on Stackoverflow
Solution 7 - .NetIadine GOUNDETEView Answer on Stackoverflow
Solution 8 - .NetJakub SzumiatoView Answer on Stackoverflow
Solution 9 - .NetMauricio SchefferView Answer on Stackoverflow
Solution 10 - .NetSteveCView Answer on Stackoverflow
Solution 11 - .NetShelby115View Answer on Stackoverflow
Solution 12 - .NetReflexiveCodeView Answer on Stackoverflow
Solution 13 - .NetDumisaView Answer on Stackoverflow
Solution 14 - .Netjk.View Answer on Stackoverflow
Solution 15 - .NetKrisztián BallaView Answer on Stackoverflow
Solution 16 - .NetsmirkingmanView Answer on Stackoverflow
Solution 17 - .NetgauravView Answer on Stackoverflow
Solution 18 - .NetJBartlauView Answer on Stackoverflow
Solution 19 - .NetJamie ClaytonView Answer on Stackoverflow
Solution 20 - .NetHamid HeydarianView Answer on Stackoverflow
Solution 21 - .NetEzhil ArasanView Answer on Stackoverflow
Solution 22 - .NetChrisView Answer on Stackoverflow
Solution 23 - .NetLarsbjView Answer on Stackoverflow
Solution 24 - .NetJeffView Answer on Stackoverflow
Solution 25 - .NetlifestyleView Answer on Stackoverflow
Solution 26 - .NetJackdon WangView Answer on Stackoverflow
Solution 27 - .NetmandersonView Answer on Stackoverflow
Solution 28 - .NetSerj SaganView Answer on Stackoverflow
Solution 29 - .NetCathalView Answer on Stackoverflow
Solution 30 - .NetBas WiebingView Answer on Stackoverflow