I’m trying to create a class from an assembly known only at runtime. Having weird problems.
string providerType = AppConfig.GetConfigValue("LocationProvider");
string assemblyFileName = AppConfig.GetConfigValue("LocationProviderAssembly");
Assembly assembly = Assembly.LoadFrom(assemblyFileName);
//Object obj = assembly.CreateInstance(providerType) ;
Type type = assembly.GetType(providerType);
Object obj = Activator.CreateInstance(type);
ILocationProvider locProvider = obj as ILocationProvider;
float distance = locProvider.GetDistance(new Location(), new Location());
If I use the debugger, and stop before the last two lines are executed, I can run those two lines in the Immediate window, and they work. But if I let the code run, locProvider remains null.
obj seems to have the right type:
obj.GetType()
{Name = "LocationProviderConcrete" FullName = "LocationProvider.LocationProviderConcrete"}
[System.RuntimeType]: {Name = "LocationProviderConcrete" FullName = "LocationProvider.LocationProviderConcrete"}
base {System.Reflection.MemberInfo}: {Name = "LocationProviderConcrete" FullName = "LocationProvider.LocationProviderConcrete"}
And this works fine in the Immediate window:
((ILocationProvider) obj).GetDistance(new Location(), new Location())
Any clues as to why this doesn’t work in the normal code flow?
Where is
ILocationProviderdeclared? My guess is that you’ve got one copy in the assembly you’re loading by reflection, and one copy in the “running” assembly. Those are different interfaces.Basically, you need to make sure that the interface is only loaded in one assembly, and only in one copy of that assembly too.
I wrote this article years ago – there may be better approaches to some aspects of it, but the fundamentals of what’s going wrong are probably still valid.