TypeLoadException says 'no implementation', but it is implemented
Asked Answered
I

42

306

I've got a very weird bug on our test machine. The error is:

System.TypeLoadException: Method 'SetShort' in type 'DummyItem' from assembly 'ActiveViewers (...)' does not have an implementation.

I just can't understand why. SetShort is there in the DummyItem class, and I've even recompiled a version with writes to the event log just to make sure that it's not a deployment/versioning issue. The weird thing is that the calling code doesn't even call the SetShort method.

Infuscate answered 4/6, 2009 at 5:58 Comment(4)
I love how your shared your experience with the community to help us all, and even encouraged us to read the other answers too, thank you. Sadly, none of suggestions worked for me. Want to know what did end up working for me? Restarting Visual Studio. Why did I not try that first?Lustful
Also, after VS 2017 15.7 update, VS tells you to reboot. You may not have done that (like me, because of meetings I forgot). I got craploads of erros like these...Ralphralston
Just to add my 2p - I got this problem when running unit tests in MsTest. The classes under test were in a signed assembly. A different version of this assembly happened to be in the GAC. MsTest was picking up the GAC'd assembly rather than using the one from the bin folder, and trying to run the tests against it, which was obviously not working. Solution was to remove the GAC'd assemblyJochbed
@PaulMcLean such an old comment and still worked ;-) I had the issue after Windows was in energy saving mode. No code changed. So this was the very first thing to try.Sulfaguanidine
I
280

NOTE - If this answer doesn't help you, please take the time to scroll down through the other answers that people have added since.

Really short answer

Delete all your bin and obj directories and rebuild everything. The versions of the dlls don't match.

Short answer

This can happen if you add a method to an interface in one assembly, and then to an implementing class in another assembly, but you rebuild the implementing assembly without referencing the new version of the interface assembly.

In this case, DummyItem implements an interface from another assembly. The SetShort method was recently added to both the interface and the DummyItem - but the assembly containing DummyItem was rebuilt referencing the previous version of the interface assembly. So the SetShort method is effectively there, but without the magic sauce linking it to the equivalent method in the interface.

Long answer

If you want to try reproducing this, try the following:

  1. Create a class library project: InterfaceDef, add just one class, and build:

     public interface IInterface
     {
         string GetString(string key);
         //short GetShort(string key);
     }
    
  2. Create a second class library project: Implementation (with separate solution), copy InterfaceDef.dll into project directory and add as file reference, add just one class, and build:

     public class ImplementingClass : IInterface
     {
         #region IInterface Members
         public string GetString(string key)
         {
             return "hello world";
         }
    
         //public short GetShort(string key)
         //{
         //    return 1;
         //}
         #endregion
     }
    
  3. Create a third, console project: ClientCode, copy the two dlls into the project directory, add file references, and add the following code into the Main method:

      IInterface test = new ImplementingClass();
      string s = test.GetString("dummykey");
      Console.WriteLine(s);
      Console.ReadKey();
    
  4. Run the code once, the console says "hello world"

  5. Uncomment the code in the two dll projects and rebuild - copy the two dlls back into the ClientCode project, rebuild and try running again. TypeLoadException occurs when trying to instantiate the ImplementingClass.

Infuscate answered 4/6, 2009 at 5:58 Comment(14)
You might need to add that the Console app should be rebuilt with the new DLLs as reference. Merely copying the DLL won't work and that could be due to version mismatch (i.e after you compile the source DLL the version will change). Is that fair understanding?Leaky
@Leaky good point - for me 'running again' implied F5. I've updated the answer. Of course all this wouldn't have happened with a decent source control tool, but don't get me started on that subject...Infuscate
Hmm, it looks like Microsoft's error message has an error in it - it's saying that a method of class "DummyItem" doesn't have an implementation, which is patently false.... really the problem is that a method of the interface isn't implemented BY DummyItem.Batting
any good final solution about it ? What solution was Microsoft recommended ?Inbreed
My problem was the inverse of this. We distributed an executable which referenced an interface DLL (and other DLLs) in a zip file along with all its dependencies. Upon getting a notice that a new build was out, a user copied everything (including the updated interface DLL) from the zip except the executable.Cubicle
The solution is to delete the bin files manually. The publish isn't viewing them as changed so you need to force it to have the latest. This really should be noted in the top rated answer!Lucier
another possible reason is when we use ILMerge to merge a few assemblies.Implicate
In my case, it was one of the argument of the method that was built using the new version. Thanks.Drainage
Marking ImplementingClass.GetShort virtual resolves the issue and the class ImplementingClass becomes "compatible" with both versions of the IInterface (even when compiled against the earlier version).Arsenite
@Infuscate Could you add the solution "delete the bin-folder" to your (apart from that quite complete) answer? Didn't want to "steal" your effort by adding a single line :)Stpeter
@OleAlbers, not sure where you wanted to add this: as another answer, or within my answer?Infuscate
My case was also deleting the bin files manually. The dlls in the bin were not being replaced it seems.Anabaptist
In my case I had an old version of the dll in the output folder, and "CopyLocal" to false, in the project settings.Coates
In my case, I was packing the assemblies as nuget packages and getting the error in another project which use those packages. I have tried to delete bin files with no luck, then I removed the problematic code, packed again and then succeeded. After that, I tried again by including the problematic code and succeeded again.Concerted
H
39

In addition to what the asker's own answer already stated, it may be worth noting the following. The reason this happens is because it is possible for a class to have a method with the same signature as an interface method without implementing that method. The following code illustrates that:

public interface IFoo
{
    void DoFoo();
}

public class Foo : IFoo
{
    public void DoFoo() { Console.WriteLine("This is _not_ the interface method."); }
    void IFoo.DoFoo() { Console.WriteLine("This _is_ the interface method."); }
}

Foo foo = new Foo();
foo.DoFoo();               // This calls the non-interface method
IFoo foo2 = foo;
foo2.DoFoo();              // This calls the interface method
Harold answered 8/7, 2009 at 18:20 Comment(1)
This solved it for me, with the added level of obfuscation that the Method it claimed was missing was declared in an interface implemented by a parent class, and declared again in the subclass. Removing the duplicate from the subclass made the error go away.Superpower
M
26

I got this when my application didn't have a reference to another assembly defining a class that the method in the error message used. Running PEVerify gave more helpful error: "The system cannot find the file specified."

Mcdade answered 16/9, 2009 at 21:31 Comment(0)
A
24

I came across the same message and here is what we have found: We use third party dlls in our project. After a new release of those was out we changed our project to point to the new set of dlls and compiled successfully.

The exception was thrown when I tried to instatiate one of the their interfaced classes during run time. We made sure that all the other references were up to date, but still no luck. We needed a while to spot (using the Object Browser) that the return type of the method in the error message was a completely new type from a new, unreferenced assembly.

We added a reference to the assembly and the error disappeared.

  • The error message was quite misleading, but pointed more or less to the right direction (right method, wrong message).
  • The exception ocurred even though we did not use the method in question.
  • Which leads me to the question: If this exception is thrown in any case, why does the compiler not pick it up?
Acis answered 5/5, 2010 at 7:3 Comment(0)
R
20

I received this error in the following scenario.

  • Both Assemblies A and B referenced System.Web.Mvc Version 3.0.0.0
  • Assembly A referenced Assembly B and had classes which implemented interfaces from Assembly B with methods which returned classes from System.Web.Mvc.
  • Assembly A upgraded to System.Web.Mvc Version 4.0.0.0
  • Assembly C ran the code below (FertPin.Classes.Contact was contained in Assembly A):

var target = Assembly.GetAssembly(typeof(FertPin.Classes.Contact));

The fix for me was upgrading the System.Web.Mvc reference in Assembly B to 4.0.0.0. Seems obvious now!

Thanks to the original poster!

Rugged answered 1/11, 2012 at 12:31 Comment(2)
I had something similar but the other way round with versions. One method, targetting .NET 2, returned a type from v2 of System.Windows.Forms. Its overridden implementation in a .NET 4-targetted assembly returned the same type but from v4 of System.Windows.Forms. It compiled fine but ReflectionOnlyLoadFrom didn't like it.Irredentist
I had a similar problem caused by loading types which targeted .NET2 into a ReflectionOnly context of a .NET4 application. I worked around the problem by redirecting all assembly requests of .NET2 core assemblies to their .NET4 counterparts in the AppDomain.ReflectionOnlyAssemblyResolve event.Gyronny
F
14

The other time you can get this error is if you have an incorrect version of a signed assembly. It's not the normal symptom for this cause, but here was the scenario where I got it

  • an asp.net project contains assembly A and assembly B, B is strongly named

  • assembly A uses Activator.CreateInstance to load assembly C (i.e. there is no reference to C which is built separately)

  • C was built referencing an older version of assembly B than is currently present

hope that helps someone - it took me ages to figure this out.

Fright answered 30/11, 2009 at 16:17 Comment(2)
Also can happen if a deployment script copies an old DLL, like when multiple releases are compiled in the same set of output folders.Tincal
More details: I added a new project and extended an interface in a later version and built. I switched to an earlier version and built. The "new" folder was still there and the DLL with the modified interface from the "unversioned" folder was copied into the new build through an external script. My fault for building in a common checkout folder. I found it by searching folders in Windows Explorer for the errant DLL; it was in a folder that wasn't part of the current build.Tincal
D
10

I had this error too, it was caused by an Any CPU exe referencing Any CPU assemblies that in turn referenced an x86 assembly.

The exception complained about a method on a class in MyApp.Implementations (Any CPU), which derived MyApp.Interfaces (Any CPU), but in fuslogvw.exe I found a hidden 'attempt to load program with an incorrect format' exception from MyApp.CommonTypes (x86) which is used by both.

Deathbed answered 18/8, 2010 at 15:13 Comment(0)
L
10

I keep coming back to this... Many of the answers here do a great job of explaining what the problem is but not how to fix it.

The solution to this is to manually delete the bin files in your projects published directory. It will clean up all the references and force the project to use the latest DLLs.

I don't suggest using the publish tools Delete function because this tends to throw off IIS.

Lucier answered 1/5, 2015 at 14:45 Comment(2)
I found this to be the case in a non web project too - I was reflecting one assembly in another (using LoadFile), clean and rebuild didn't work - deleting all files from the bin folder of both projects did work. Cheers for the suggestion!Circuitous
I had to do an IIS reset as well since this particular project is using IIS locally (unfortunately).Lugworm
K
7

I encountered this error in a context where I was using Autofac and a lot of dynamic assembly loading.

While performing an Autofac resolution operation, the runtime would fail to load one of the assemblies. The error message complained that Method 'MyMethod' in type 'MyType' from assembly 'ImplementationAssembly' does not have an implementation. The symptoms occurred when running on a Windows Server 2012 R2 VM, but did not occur on Windows 10 or Windows Server 2016 VMs.

ImplementationAssembly referenced System.Collections.Immutable 1.1.37, and contained implementations of a IMyInterface<T1,T2> interface, which was defined in a separate DefinitionAssembly. DefinitionAssembly referenced System.Collections.Immutable 1.1.36.

The methods from IMyInterface<T1,T2> which were "not implemented" had parameters of type IImmutableDictionary<TKey, TRow>, which is defined in System.Collections.Immutable.

The actual copy of System.Collections.Immutable found in the program directory was version 1.1.37. On my Windows Server 2012 R2 VM, the GAC contained a copy of System.Collections.Immutable 1.1.36. On Windows 10 and Windows Server 2016, the GAC contained a copy of System.Collections.Immutable 1.1.37. The loading error only occurred when the GAC contained the older version of the DLL.

So, the root cause of the assembly load failure was the mismatching references to System.Collections.Immutable. The interface definition and implementation had identical-looking method signatures, but actually depended on different versions of System.Collections.Immutable, which meant that the runtime did not consider the implementation class to match the interface definition.

Adding the following binding redirect to my application config file fixed the issue:

<dependentAssembly>
        <assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.1.37.0" newVersion="1.1.37.0" />
</dependentAssembly>
Kiwanis answered 23/3, 2017 at 7:31 Comment(4)
Can I ask you how you found it? Did you use any non-standard debugging technique? I get the same error but I think it's caused by a different dll as I already have a binding redirect for the immutables.Benelux
Hmm. It was a while ago. I think the main clue was that the "unimplemented" method's parameters used types from System.Collections.Immutable. In my case there weren't many other candidate parameter or return types in the affected method. I also remember using ILSpy to inspect the dependency metadata in the compiled "DefinitionAssembly" and "ImplementationAssembly" DLLs, specifically looking at the versions of the references.Kiwanis
Thanks so much! ;-) I installed the ILSpy extension for Visual Studio and looked at the References branch, there was one for the System.Net.Http package, I added the dependentAssembly element for it and copied the info from ILSpy and it's working now, the error is gone!Benelux
I figured out which was the bad GAC assembly by putting this in the code and putting a breakpoint right after it to look at the values and seeing two versions of System.Net.Http were loaded: var loadedAssemblies = from a in AppDomain.CurrentDomain.GetAssemblies() orderby a.FullName select (a.FullName, a);Balky
P
6

I got this with a "diamond" shaped project dependency:

  • Project A uses Project B and Project D
  • Project B uses Project D

I recompiled project A but not Project B, which allowed Project B to "inject" the old version of the Project D dll

Provencher answered 23/9, 2010 at 9:9 Comment(1)
I think I had a similar version of this problem, but just between two projects. I compiled the new one manually. After that it worked smoothly.Substation
A
6

I have yet another esoteric solution to this error message. I upgraded my target framework from .Net 4.0 to 4.6, and my unit test project was giving me the "System.TypeLoadException...does not have an implementation" error when I tried to build. It also gave a second error message about the same supposedly non-implemented method that said "The 'BuildShadowTask' task failed unexpectedly." None of the advice here seemed to help, so I searched for "BuildShadowTask", and found a post on MSDN which led me to use a text editor to delete these lines from the unit test project's csproj file.

<ItemGroup>
  <Shadow Include="Test References\MyProject.accessor" />
</ItemGroup>

After that, both errors went away and the project built.

Andra answered 13/11, 2015 at 23:42 Comment(1)
This was the answer for me. I ran into this error after I upgraded from .NET 4.5 to 4.6.Kantianism
I
5

I encountered this when I renamed a project (and the assembly name), which was depended upon by an ASP.NET project. Types in the web project implemented interfaces in the dependent assembly. Despite executing Clean Solution from the Build menu, the assembly with the previous name remained in the bin folder, and when my web project executed

var types = AppDomain.CurrentDomain.
   GetAssemblies().
   ToList().
   SelectMany( s => s.GetTypes() /* exception thrown in this call */ )
;

the above exception was thrown, complaining that interface methods in the implementing web types were not actually implemented. Manually deleting the assembly in the web project's bin folder resolved the problem.

Ir answered 27/5, 2012 at 6:39 Comment(0)
S
4

FWIW, I got this when there was a config file that redirected to a non-existent version of a referenced assembly. Fusion logs for the win!

Shandeigh answered 10/12, 2009 at 17:54 Comment(0)
S
4

I also got this error when I had previously enabled Code Coverage during unit testing for one of the assemblies. For some reason Visual Studio "buffered" the old version of this particular DLL even though I had updated it to implement a new version of the interface. Disabling Code Coverage got rid of the error.

Sucking answered 26/9, 2010 at 8:2 Comment(0)
H
4

This error can also be caused if an assembly is loaded using Assembly.LoadFrom(String) and is referencing an assembly that was already loaded using Assembly.Load(Byte[]).

For instance you have embedded the main application's referenced assemblies as resources but your app loads plug-ins from a specific folder.

Instead of using LoadFrom you should use Load. The following code will do the job:

private static Assembly LoadAssemblyFromFile( String filePath )
{
    using( Stream stream = File.OpenRead( filePath ) )
    {
        if( !ReferenceEquals( stream, null ) )
        {
            Byte[] assemblyData = new Byte[stream.Length];
            stream.Read( assemblyData, 0, assemblyData.Length );
            return Assembly.Load( assemblyData );
        }
    }
    return null;
}
Haynie answered 11/11, 2011 at 15:45 Comment(0)
F
4

I got this error because I had a class in an assembly 'C' which was on version 4.5 of the framework, implementing an interface in assembly 'A' which was on version 4.5.1 of the framework and serving as the base class to assembly 'B' which was also on version 4.5.1 of the framework. The system threw the exception while trying to load assembly 'B'. Additionally, I had installed some nuget packages targeting .net 4.5.1 on all three assemblies. For some reason, even though the nuget references were not showing in assembly 'B', it was building successfully.

It turned out that the real issue was that the assemblies were referencing different versions of a nuget package that contained the interface and the interface signature had changed between versions.

Fullback answered 3/8, 2015 at 5:5 Comment(0)
S
3

Another explanation for this type of problem involving managed C++.

If you try to stub an interface defined in an assembly created using managed C++ that has a special signature you will get the exception when the stub is created.

This is true for Rhino Mocks and probably any mocking framework that uses System.Reflection.Emit.

public interface class IFoo {
  void F(long bar);
};

public ref class Foo : public IFoo {
public:
  virtual void F(long bar) { ... }
};

The interface definition gets the following signature:

void F(System.Int32 modopt(IsLong) bar)

Note that the C++ type long maps to System.Int32 (or simply int in C#). It is the somewhat obscure modopt that is causing the problem as stated by Ayende Rahien on the Rhino Mocks mailing list .

Sotos answered 12/5, 2011 at 15:7 Comment(1)
I had this error when I used the datatype System::Byte. I changed the signature to accept an unsigned short and the sky was blue again.Unexpected
C
3

I just upgraded a solution from MVC3 to MVC5, and started receiving the same exception from my Unit test project.

Checked all the references looking for old files, eventualy discovered I needed to do some bindingRedirects for Mvc, in my unit test project.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
Chinaman answered 25/3, 2014 at 1:21 Comment(0)
S
3

In my case it helped to reset the WinForms Toolbox.

I got the exception when opening a Form in the designer; however, compiling and running the code was possible and the code behaved as expected. The exception occurred in a local UserControl implementing an interface from one of my referenced libraries. The error emerged after this library was updated.

This UserControl was listed in the WinForms Toolbox. Probably Visual Studio kept a reference on an outdated version of the library or was caching an outdated version somewhere.

Here is how I recovered from this situation:

  1. Right click on the WinForms Toolbox and click on Reset Toolbox in the context menu. (This removes custom items from the Toolbox).
    In my case the Toolbox items were restored to their default state; however, the Pointer-arrow was missing in the Toolbox.
  2. Close Visual Studio.
    In my case Visual Studio terminated with a violation exception and aborted.
  3. Restart Visual Studio.
    Now everything is running smoothly.
Skelp answered 17/9, 2014 at 19:30 Comment(0)
M
3

In my case I had previously referenced a mylib project in a sibling folder outside of the repo - let's call that v1.0.

|-- myrepo
|    |-- consoleApp
|    |-- submodules
|         |-- mylib (submoduled v2.0)
|-- mylib (stale v1.0)

Later I did it properly and used it via a git submodule - lets call that v2.0. One project consoleApp however wasn't updated properly. It was still referencing the old v1.0 project outside of my git project.

Confusingly, even though the *.csproj was plainly wrong and pointing to v1.0, the Visual Studio IDE showed the path as the v2.0 project! F12 to inspect the interface and class went to the v2.0 version too.

The assembly placed into the bin folder by the compiler was the v1.0 version, hence the headache.

That fact that the IDE was lying to me made it extra hard to realise the error.

Solution: Deleted project references from ConsoleApp and readded them.

General Tip: Recompile all assemblies from scratch (where possible, can't for nuget packages of course) and check datetime stamps in bin\debug folder. Any old dated assemblies are your problem.

Maidamaidan answered 28/10, 2016 at 11:27 Comment(0)
R
3

I faced almost same issue. I was scratching my head what is causing this error. I cross checked, all the methods were implemented.

On Googling I got this link among other. Based on @Paul McLink comment, This two steps resolved the issue.

  1. Restart Visual Studio
  2. Clean, Build (Rebuild)

and the error gone.

Restart VS Plugin

Thanks Paul :)

Hope this helps someone who come across this error :)

Repeal answered 10/2, 2017 at 13:18 Comment(0)
I
2

I got this in a WCF service due to having an x86 build type selected, causing the bins to live under bin\x86 instead of bin. Selecting Any CPU caused the recompiled DLLs to go to the correct locations (I wont go into detail as to how this happened in the first place).

Infection answered 28/7, 2009 at 14:16 Comment(0)
D
2

I also ran into this problem while running my unittests. The application ran fine and with no errors. The cause of the problem in my case was that I had turned off the building of the test projects. Reenabling the building of my testprojects solved the issues.

Danged answered 10/9, 2012 at 11:38 Comment(0)
B
2

I saw this in Visual Studio Pro 2008 when two projects built assemblies with the same name, one a class lib SDF.dll, and one that referenced the lib with assembly name sdf.exe. When I changed the name of the referencing assembly, the exception went away

Blenheim answered 9/11, 2012 at 17:22 Comment(0)
D
2

This simply means that the implementation project is out of date in my cases. The DLL containing the interface was rebuilt but the implementation dll was stale.

Denture answered 16/9, 2013 at 4:2 Comment(0)
M
2

Here's my take on this error.

Added an extern method, but my paste was faulty. The DllImportAttribute got put on a commented out line.

/// <returns>(removed for brevity lol)</returns>[DllImport("user32.dll")] 
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWindowVisible(IntPtr hWnd);

Ensuring the attribute was actually included in source fixed the issue.

Macerate answered 1/4, 2015 at 19:30 Comment(0)
C
2

It happened to me when an interface had a reference to 3rd party dll (MWArray) with 'Specific Version' set to 'True' while the implemented class had a reference to the same dll but with 'Specific Version' set to 'False', so class and interface had different versions reference to the same dll.

Setting both to 'Specific Version': 'False' or 'True' (depending on what you need) fixed it.

Cymar answered 13/6, 2021 at 12:17 Comment(0)
D
2

I got this issue when I tried to implement plugin assembly loading in dot net 5 using custom AssemblyLoadContext (without AppDomain creation) and shared type (interface which you need to use to call plugin methods without reflection). Nothing from this thread helped me. Here is what I did to solve this issue:

  1. To allow debugging of plugin loading without a problems - setup project output path to host app bin folder. You will debug the same assembly you got after plugin project build. This is, probably, temporary change (just for debug).
  2. To fix TypeLoadException you need to load all 'contract assembly' referenced assemblies as shared assemblies (except runtime assemblies). Check loader context implementation (loading sharedAssemblies in constructor):

    public class PluginAssemblyLoadContext : AssemblyLoadContext
    {
        private AssemblyDependencyResolver _resolver;
        
        private IDictionary<string, Assembly> _loadedAssemblies;
        
        private IDictionary<string, Assembly> _sharedAssemblies;

        private AssemblyLoadContext DefaultAlc;

        private string _path;

        public PluginAssemblyLoadContext(string path, bool isCollectible, params Type[] sharedTypes)
             : this(path, isCollectible, sharedTypes.Select(t => t.Assembly).ToArray())
        {
        }

        public PluginAssemblyLoadContext(string path, bool isCollectible, params Assembly[] sharedAssemblies)
             : base(isCollectible: isCollectible)
        {

            _path = path;

            DefaultAlc = GetLoadContext(Assembly.GetExecutingAssembly()) ?? Default;

            var fileInfo = new FileInfo(_path);
            if (fileInfo.Exists)
            {
                _resolver = new AssemblyDependencyResolver(_path);

                _sharedAssemblies = new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);
                foreach (var a in sharedAssemblies.Distinct())
                {
                    LoadReferencedAssemblies(a);
                }

                _loadedAssemblies = new Dictionary<string, Assembly>();

                var assembly = LoadFromAssemblyPath(fileInfo.FullName);

                _loadedAssemblies.Add(fileInfo.FullName, assembly);
            }
            else
            {
                throw new FileNotFoundException($"File does not exist: {_path}");
            }
        }

        public bool LoadReferencedAssemblies(Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }
            if (string.IsNullOrEmpty(assembly.Location))
            {
                throw new NotSupportedException($"Assembly location is empty string or null: {assembly.FullName}");
            }
            var alc = GetLoadContext(assembly);
            if (alc == this)
            {
                throw new InvalidOperationException($"Circular assembly loader dependency detected");
            }
            if (!_sharedAssemblies.ContainsKey(assembly.Location))
            {
                _sharedAssemblies.Add(assembly.Location, assembly);

                foreach (var an in assembly.GetReferencedAssemblies())
                {
                    var ra = alc.LoadFromAssemblyName(an);
                    LoadReferencedAssemblies(ra);
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        public IEnumerable<Type> GetCommandTypes<T>()
        {
            var cmdType = typeof(T);
            return _loadedAssemblies.Values.SelectMany(a => a.GetTypes()).Where(t => cmdType.IsAssignableFrom(t));
        }

        public IEnumerable<T> CreateCommands<T>(Assembly assembly)
        {
            foreach (var cmdType in GetCommandTypes<T>())
            {
                yield return (T)Activator.CreateInstance(cmdType);
            }
        }

        protected override Assembly Load(AssemblyName assemblyName)
        {
            var path = _resolver.ResolveAssemblyToPath(assemblyName);
            if (path != null)
            {
                if (_sharedAssemblies.ContainsKey(path))
                {
                    return _sharedAssemblies[path];
                }
                if (_loadedAssemblies.ContainsKey(path))
                {
                    return _loadedAssemblies[path];
                }
                return LoadFromAssemblyPath(path);
            }     
            return DefaultAlc.LoadFromAssemblyName(assemblyName);
        }
    }

Usage:


var loader = new PluginAssemblyLoadContext(fullPath, false, typeof(IPluginCommand));
loader.CreateCommands<IPluginCommand>()...
Douzepers answered 20/9, 2021 at 9:39 Comment(0)
W
1

I had the same problem. I figured out that my assembly, which is loaded by the main program, had some references with "Copy Local" set to true. These local copies of references were looking for other references in the same folder, which did not exist because the "Copy Local" of other references was set to false. After the deletion of the "accidentally" copied references the error was gone because the main program was set to look for correct locations of references. Apparently the local copies of the references screwed up the sequence of calling because these local copies were used instead of the original ones present in the main program.

The take home message is that this error appears due to the missing link to load the required assembly.

Wireman answered 4/1, 2016 at 7:57 Comment(0)
D
1

In my case, I was attempting to use TypeBuilder to create a type. TypeBuilder.CreateType threw this exception. I eventually realized that I needed to add MethodAttributes.Virtual to the attributes when calling TypeBuilder.DefineMethod for a method that helps implements an interface. This is because without this flag, the method does not implement the interface, but rather a new method with the same signature instead (even without specifying MethodAttributes.NewSlot).

Dibru answered 21/12, 2016 at 15:3 Comment(0)
I
1

As an addendum: this can also occur if you update a nuget package that was used to generate a fakes assembly. Say you install V1.0 of a nuget package and create a fakes assembly "fakeLibrary.1.0.0.0.Fakes". Next, you update to the newest version of the nuget package, say v1.1 which added a new method to an interface. The Fakes library is still looking for v1.0 of the library. Simply remove the fake assembly and regenerate it. If that was the issue, this will probably fix it.

Indohittite answered 20/1, 2017 at 21:13 Comment(0)
S
1

I received this error after a recent windows update. I had a service class set to inherit from an interface. The interface contained a signature that returned a ValueTuple, a fairly new feature in C#.

All I can guess is that the windows update installed a new one, but even explicitly referencing it, updating binding redirects, etc...The end result was just changing the signature of the method to something "standard" I guess you could say.

Series answered 13/12, 2017 at 13:47 Comment(0)
J
1

Just to add my experience as it has not been covered in other answers:

I got this problem when running unit tests in MsTest.

The classes under test were in a signed assembly.

A different version of this assembly happened to be in the GAC (but with the same assembly version number).

Dependency resolution algorithm for strong named assemblies is slightly different to non-signed as the GAC is checked first.

So MsTest was picking up the GAC'd assembly rather than using the one from the bin folder, and trying to run the tests against it, which was obviously not working.

Solution was to remove the GAC'd assembly.

Note, the clue for me was this was not happening on the build server when the tests were run, because the build would compile the assemblies with a new assembly version number. This meant that older versions of the assembly in the GAC would not be picked up.

Also, I found a potential workaround here, if you cannot for some reason access the GAC: https://johanleino.wordpress.com/2014/02/20/workaround-for-unit-testing-code-that-reside-in-the-gac/

Jochbed answered 27/6, 2018 at 14:11 Comment(0)
C
1

I get this error today. My problem was - do not doing in TFS get latest version. In server was dll with interface whic one of methods was modified. I worked with an old one - in my PC its works. How to fix: get latest, rebuild

Casey answered 22/11, 2018 at 12:4 Comment(0)
H
1

Yet another way to get this:

class GenericFoo<T> {}

class ConcreteFoo : GenericFoo<ClassFromAnotherAssembly> {}

Code in an assembly that doesn't reference the assembly of ClassFromAnotherAssembly.

var foo = new ConcreteFoo(); //kaboom

This happened to me when ClassFromAnotherAssembly was ValueTuple.

Harness answered 10/1, 2019 at 17:16 Comment(0)
C
1

We had the same issue. It turned out to be a version mismatch between a library referenced by our console app and the library referenced by our data access library.

I realise answers similar to this have been posted before but feel the addition of pictures should really help.

When you reference a class library, you think of the references as a hierarchical tree. App A references Library B, which in turn references library C (see picture below).

How you imagine references

In reality however it's more tangled than that (at least in .net Framework). Your app must not only reference the class library it uses but also all the dependencies of that class library. App A references Library B and Library C. Library B references Library C

How it actually is

The problem arises when Library B references a different version of Library C to the version of Library C that App A references

This doesn't work

If you look at your method signature you'll find a type that's from library C. That should tell you which library to check the version of.

Combs answered 14/12, 2023 at 15:57 Comment(0)
H
0

I ran into this and only my local machine was having the problem. No other developers in our group nor my VM had the problem.

In the end it seemed to be related to a "targeting pack" Visual Studio 2017

  • Open the Visual Studio Installer
  • Select Modify
  • Go to the second top tab "Individual Components"
  • See what Frameworks and Targeting packs you have selected.
  • I did not have the two newest targeting packs selected
  • I also noticed I did not have "Advanced ASP.NET features" selected and the other machines did.
  • Selected and installed the new items and it is all good now.
Honeyman answered 28/9, 2018 at 14:36 Comment(0)
D
0

Our problem solved with updating windows! Our web application is on .Net 4.7.1 and c# 7.0. As we tested in different windowses, we understood that the problem will be solved by updating windows. Indeed, the problem was seen in windows 10 (version 1703) and also in a windows server 2012(not updated in last year). After updating both of them, the problem was solved. In fact, the asp.net minor version(the third part of the clr.dll version in C:\Windows\Microsoft.NET\Framework64\v4.0.30319 ) was changed a bit after the update.

Dalesman answered 16/5, 2019 at 6:20 Comment(0)
S
0

I had this error when my integration test project was trying to load a DLL which didn't contain dependency resolution for an interface:

  1. Integration Test Project (references Main Project but not StructureMap)
  2. Main Project (references StructureMap project - uses Interface in class constructor)
  3. StructureMap Project (IoC - For().Use();)

This caused the error to be thrown because it couldn't find the concrete implementation. I excluded the DLL in my test configuration and the error disappeared

Subvert answered 26/12, 2019 at 13:46 Comment(0)
M
0

The solution for me was related to the fact that the project that was implementing the interface had the property "Register for COM Interop" set. Unchecking this option resolved the issue for me.

Mcleroy answered 15/10, 2020 at 16:21 Comment(0)
G
0

What solved the problem for me was to add the following to ProjectReference and/or PackageReference along with <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> in the Assembly which was being loaded:

<Private>false</Private>
<ExcludeAssets>runtime</ExcludeAssets>

This then made my project file look something like this:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
  </PropertyGroup>

  <!-- For a package -->
  <ItemGroup>
    <PackageReference Include="SomePackage" Version="x.x.x.x">
      <Private>false</Private>
      <ExcludeAssets>runtime</ExcludeAssets>
    </PackageReference>
  </ItemGroup>

  <!-- For a project -->
  <ItemGroup>
    <ProjectReference Include="..\SomeProject\SomeProject.csproj">
      <Private>false</Private>
      <ExcludeAssets>runtime</ExcludeAssets>
    </ProjectReference>
  </ItemGroup>
</Project>
Grekin answered 7/3, 2021 at 14:11 Comment(0)
S
-1

Another possibility is a mixture of release and debug builds in the dependencies. For example, Assembly A depends on Assembly B, A was built in Debug mode while the copy of B in GAC was built in Release mode, or vice versa.

Sohn answered 20/5, 2015 at 13:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.