Reputation: 25927
I'll mostly probably need to load the same assembly dynamically multiple times. My questions are:
Upvotes: 0
Views: 1124
Reputation: 941455
It depends on the loading context of the assembly load. That's a hundred dollar word that's hard to explain in an SO answer, Suzanne Cook's blog goes into the concept in detail. In a nutshell, the context permits the CLR to figure out whether an assembly was loaded before and where it should look for dependent assemblies.
It is easier to explain what can go wrong. Both Assembly.LoadFile()
and Assembly.Load(byte[])
loads assemblies without a context. With the quirk that this allows an assembly to be loaded more than once since the CLR cannot determine if the assembly that's getting loaded by them was previously loaded. For LoadFile() this is intentional, in very select cases you want to allow to load an assembly again. For Load(byte[]) it is in inevitable accident, the CLR doesn't know enough about the identity of the assembly since it cannot know its display name.
This is almost always bad, types in .NET have an identity that isn't just the namespace name + type name, it also includes the assembly that the type was loaded from. You tend to get hard to diagnose InvalidCastExceptions that read like "Unable to cast object of type Foo.Bar to type Foo.Bar". That leads to clumps of head hair being lost on trying to figure out what that means and what causes it.
Watch out for Assembly.LoadFile(), its name is entirely too innocent looking and it very rarely does what you want it to do. Use LoadFrom() instead. Load(byte[]) is similarly dangerous and a very poor substitute for a proper installer.
Upvotes: 4
Reputation: 62472
You can't load the same assembly multiple times into the same application domain, and unless the assembly has changed it wouldn't make a lot of sense to, either.
If you do want to repeatidly load an assembly then you need to load it into a different appdomain and then unload the appdomain in order to unload the assembly. The reason for this is there is no explicit way to unload an assembly, only an appdomain.
Upvotes: 1