I'm trying to load dll's at runtime and use types within them.
Unfortunately I'm running into some strange issues that I don't fully understand. Here's a minimal version of the code that demonstrates the problem:
public class Component
{
}
class Program
{
static void Main()
{
Assembly assembly = Assembly.LoadFile(Assembly.GetExecutingAssembly().Location);
var componentType = assembly.GetExportedTypes().FirstOrDefault(x => x.Name == "Component");
Console.WriteLine(componentType == typeof(Component));
ConstructorInfo constructor = componentType.GetConstructors()[0];
var component = constructor.Invoke(new object[0]);
var k = (Component)component;
}
}
In the console, it prints 'False', and when I try to do the cast it crashes with:
System.InvalidCastException:
[A]TypeTest.Component cannot be cast to [B]TypeTest.Component.
Type A originates from 'TypeTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\Users\Home\Documents\TypeTest\TypeTest\bin\Debug\net6.0\TypeTest.dll'.
Type B originates from 'TypeTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\Users\Home\Documents\TypeTest\TypeTest\bin\Debug\net6.0\TypeTest.dll'.
Ultimately I'm going to be using dependency injection across dynamically loaded dll's, which works, but doesn't obey the singleton scope as it's treating the types as different even though they are referring to the same class in the same codebase.
Aucun commentaire:
Enregistrer un commentaire