Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Types loaded from an assembly file are not equal to the same type when referenced in .NET Core

Tags:

c#

.net

.net-core

I take a Type, query its assembly location, and then load the assembly from the same address, and find the same type from the loaded assembly. The resulting type is not equal to the original type.

Here's the test case:

[TestMethod]
public void TestTypeLoadingWithFilePath()
{
    var originalType = typeof(SomeClass);
    var assemblyAddress = originalType.Assembly.Location;

    var loadedAssembly = Assembly.LoadFile(assemblyAddress);
    Assert.IsNotNull(loadedAssembly);

    var loadedType = loadedAssembly.GetType(originalType.FullName);
    Assert.IsNotNull(loadedType);

    Assert.AreEqual(originalType, loadedType);
}

The test fails on the last assertion.

This only happens on .NET Core on Windows. (I'm testing against latest version, 2.1.4). But this was not the case with .NET Framework.

My questions are:

  • Is this by design, or a bug?
  • If it's by design, why?
  • Again, if it's by design, doesn't this mean different behavior between two implementations of .NET Standard? (.NET Core vs. .NET Framework)
like image 433
Iravanchi Avatar asked Feb 09 '18 18:02

Iravanchi


1 Answers

This is a normal behavior. Using Assembly.LoadFile will load the assembly and create a new "instance" of it. To fix this, simply use Assembly.LoadFrom instead. This will first look in the current context if the requested assembly is already loaded, and take this one if it is. Comparing types like you're doing will then work.

Edit: I don't know if it's intended, but this method works in both .NetFramework and .NetCore.

like image 89
Philippe Paré Avatar answered Oct 17 '22 05:10

Philippe Paré