156

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.

Grace Note
  • 3,205
  • 4
  • 35
  • 55
George Mauer
  • 117,483
  • 131
  • 382
  • 612

30 Answers30

152

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

AndrewS
  • 3,450
  • 1
  • 21
  • 26
  • 3
    In addition: try to cleanup output folder. Probably, library renaming can cause the same issue, because both of them (old and new) will be placed in the same output folder. – Manushin Igor Jul 21 '15 at 21:56
  • 1
    If you cut + paste a project and don't correctly edit all the fields, it can lead to this issue! – Michael Parker Dec 04 '15 at 17:47
  • 1
    This was it for me, I had already referenced the Assembly in the referenced class library. I had to go into the web.config file of my web project and remove the reference after uninstalling the package in nuGet to make it work. – Ivan Mar 04 '19 at 16:33
128

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.

Johann
  • 4,107
  • 3
  • 40
  • 39
Eric Schoonover
  • 47,184
  • 49
  • 157
  • 202
  • 1
    I added the assemblies by browsing to the dll files, so the GAC shouldn't be entering into the equation. Also right click on the assembly->open in reflector from the solution explorer brings it up in the reflector with all the information that I would expect – George Mauer Sep 24 '08 at 01:26
  • 7
    It doesn't matter how you added it if an assembly with the same name/version exists in the GAC it will load that one. – Eric Schoonover Sep 24 '08 at 06:12
  • 1
    VS.NET will list the path to the assembly you select and reflector will open the right assembly but when the application executes the .NET runtime will load the GAC'd assembly. – Eric Schoonover Sep 24 '08 at 06:13
  • It has been a long time since I posted this issue but for the sake of storing knowledge it did indeed have something to do with overriding assemblies. Namely, I think I was using Rhino.Mocks which has its own version of castle compiled in. I had to change it so that my code was not referencing this – George Mauer May 08 '09 at 17:38
  • Awesome this just fixed my problem. I was getting the error Could not load type 'Microsoft.Data.Objects.EntityConfiguration`1' from assembly 'Microsoft.Data.Entity.Ctp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. So I just uninstalled EF CTP 4 and all worked. Cheers – superlogical Aug 13 '10 at 14:01
  • 11
    This is the second time this answer has saved my butt. I'd vote it up again if I could. – whybird Sep 21 '11 at 01:47
  • 20
    (GAK. Say it out loud. The very sound of the name warns you of what it is like.) – whybird Sep 21 '11 at 01:48
18

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.

Matt
  • 7,004
  • 11
  • 71
  • 117
18

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.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Brian Moeskau
  • 20,103
  • 8
  • 71
  • 73
  • 1
    Had something very similar, only difference was the web.config reference to the DLL was still deployed in the bin directory. This binary, in turn was referencing an old version of a shared DLL which caused the exception. – santos May 21 '19 at 15:09
9

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
Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
CJSewell
  • 183
  • 2
  • 8
9

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.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Michael Maddox
  • 12,331
  • 5
  • 38
  • 40
5

If this error is caused by changing the namespace, make sure 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 their nodes

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

MarkyMark
  • 13
  • 1
  • 5
  • The folder does not matter, but I forgot to change the project default name space after moving around and renaming projects. Thanks for pointing me into the right direction. – cdonner Dec 29 '20 at 03:26
4

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.

Jakub Szumiato
  • 1,318
  • 1
  • 14
  • 19
  • Is there a way to make FUSLOGVW work with Visual Studio Designer? Visual Studio Designer throws an exception when I try to edit one of my dialogs ("Method not found"), for a method I know exists (the app runs fine). As far as I can see, nothing shows up in FUSLOGVW when editing something in Visual Studio Designer. – Jimmy Jun 28 '18 at 19:29
3

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

Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275
  • Interesting, I got the latest build here: http://builds.castleproject.org/cruise/DownloadBuild.castle?number=956 Its what they recommended on their forum. Also if that was the case I imagine that the project wouldn't compile at all. But this compiles no problem – George Mauer Sep 24 '08 at 01:20
  • As for having the version in the GAC, I probably do, but I did not add the reference from the GAC and using reflector on the reference indicates that it is the one I thought – George Mauer Sep 24 '08 at 01:44
  • Try removing the duplicate assembly from the GAC, I'm willing to be that is your issue. – Eric Schoonover Sep 24 '08 at 06:14
3

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.

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
3

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.

Shelby115
  • 2,816
  • 3
  • 36
  • 52
3

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

ReflexiveCode
  • 256
  • 3
  • 7
3

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

SteveC
  • 15,808
  • 23
  • 102
  • 173
2

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.

Dumisa
  • 56
  • 3
  • Honestly the error message could be FAR better and indicate the dependency issue directly instead of "one of your million dependencies has a problem". – Shiv Sep 13 '21 at 01:53
2

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

jk.
  • 13,817
  • 5
  • 37
  • 50
2

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.

smirkingman
  • 6,167
  • 4
  • 34
  • 47
2

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.

maxhb
  • 8,554
  • 9
  • 29
  • 53
gaurav
  • 21
  • 1
2

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.

JBartlau
  • 772
  • 5
  • 23
  • I should note that this solution applies to cases where you're giving your assemblies to third parties and cannot make sure everyone updates just in time when you do. Otherwise, a recompile with the corrected references is preferable. – JBartlau Aug 31 '18 at 13:33
1

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.

Hamid Heydarian
  • 802
  • 9
  • 16
1

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

Ezhil Arasan
  • 450
  • 3
  • 5
  • 2
    I'll note that adding things to the GAC is usually a bad idea, make deployment harder, and is generally something that even microsoft is backing away from. – George Mauer May 20 '15 at 16:50
1

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.

Chris
  • 11
  • 1
1

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.

Larsbj
  • 28
  • 4
  • 14
1

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

Jeff
  • 155
  • 1
  • 10
1

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.

Cathal
  • 11
  • 1
  • Hi Cathal, It's difficult to visualize your instructions. Answers are given in response to specific questions, but remain in place for others to refer to. It appears you might assume that the person who reads this already has the same level of knowledge as yourself, but in many cases they don't. Is there a way you can improve it and maybe provide clear steps with examples to assist future readers? – quinny Oct 07 '21 at 11:40
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 07 '21 at 11:40
1

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

Jamie Clayton
  • 1,007
  • 11
  • 24
0

I want to mention additional things and make a conclusion.

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

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

An Example (which occurred for me)

Consider a struct that defines a nullable field of its own type inside itself. Defining such a field non-nullable, will take you a compile-time error and prevents you from building (Obviously This behaviour has a logical reason). But what about a nullable struct field instead? Actually, nullable value-types are Nullable<T> in code behind. As the c# compiler did not prevent me from defining it in this way, I tried it and built the project. But I get runtime exception System.TypeLoadException: 'Could not load type 'SomeInfo' from the assembly ... ', And It seems to be a problem in loading the part of my code (otherwise, we may say: the compiler not truly performed the 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 threw away all bin directories and refreshed the whole project. Even though I created a new project in a fresh solution and tested it, the struct generates the exception.)

It seems to be a runtime limitation (logically or technically) or a bug or the same problem else because Visual Studio not prevents me from compiling 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 idea to explain in detail why this behaviour occurs in my environment, But I faced this situation.

Conclusion

Check the situations:

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

  • When re-compilation was needed but not performed automatically (therefore the referenced assembly is not updated) and there is a 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 a need to clean some things up or causing to reset some things.

  • 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 a need to update the configuration or clean some things 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 the runtime to execute the compiled assembly, (for example when the compiler compiled a problematic code that the in-using runtime cannot understand or execute), as I faced.

lifestyle
  • 188
  • 1
  • 12
0

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.

Jackdon Wang
  • 369
  • 2
  • 6
0

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.

manderson
  • 837
  • 1
  • 6
  • 18
0

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

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
-2

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

Bas Wiebing
  • 139
  • 4
  • 5
    I'm sorry but this has nothing to do with the question, makes assumptions about using iis, and doesn't explain what's going on to cause the issue. – George Mauer Apr 03 '15 at 14:43