0

I'm creating type by name to put them to DI container. For any reason the DI container fails to register/resolve types created this way:

Type interfaceTypeFromAssembly = Assembly.LoadFrom(InterfacesAssemblyPath).GetTypes().First(t => t.Name == interfaceName);
Type implementorTypeFromAssembly = Assembly.LoadFrom(ApplicationAssemblyPath).GetTypes().First(t => t.Name == implementorClassName);

I compared types and found that:

Type implClassType= typeof(ImplClass);
Type implClassType2= typeof(ImplClass);
bool res = implClassType == implClassType2; // True

res = implClassType == implementorTypeFromAssembly; // False

The last line gives False although types have the same GUID.

What's the reason of such a behavior?

amplifier
  • 1,793
  • 1
  • 21
  • 55

1 Answers1

1

The types are different because typeof(ImplClass) loads type from assembly that is already loaded in app domain and Assembly.LoadFrom(InterfacesAssemblyPath) loads the assembly again. This means the Assembly object instance returned from Assembly.LoadFrom is new including new instances of all types.

There is no reason to use Assembly.LoadFrom when the assembly is already loaded in app domain. In this case you should acquire Assembly object from app domain. For example via Assembly.GetAssembly(SomeTypeInAssembly) or typeof(SomeTypeInAssembly).Assembly.

EDIT:

If you do not have any SomeTypeInAssembly or you do not want to use it you can use AppDomain.CurrentDomain.GetAssemblies().Single(assembly => assembly.GetName().Name == name).

Martin Volek
  • 1,079
  • 3
  • 12
  • 27
  • Ok, but all that I have is class name, which is string. Should I do something like _Type.GetType("ClassNameFromAssembly")_ and then pass is to GetAssembly? – amplifier Nov 14 '18 at 12:23
  • 1
    If you want to get `Assembly` object by name, you can use `AppDomain.CurrentDomain.GetAssemblies().Single(assembly => assembly.GetName().Name == name)` – Martin Volek Nov 14 '18 at 12:25
  • Thank you. Now it works! _Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == "ServerApp.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); Type typeFromAssembly = assembly.GetType("ServerApp.UnitTests.MyType");_ But I'm still wondering why _var assembly = Assembly.GetAssembly(Type.GetType("ServerApp.UnitTests.MyType"));_ doesn't work? – amplifier Nov 14 '18 at 12:37