Reputation: 1475
I have several applications which are required to use the same assembly. This assembly may be changed regularly, and can be installed by different MSIs
. For this reason, I do not want to put it in the GAC
, it can become a deployment nightmare over time.
If I turn the CopyLocal
attribute for this assembly to NO in the application, how do I tell the runtime
where to look for the assembly?
E.g. the application is loaded in C:/Program Files/<some directory>/bin
The DLL
is in C:/<some other directory>
Is it thus possible to load the assembly
in this way?
I've had a look at <codebase>
, but I'm not sure the assembly can be strongly signed. And probing
seems to work only for the private paths specified as subdirectories of the application?
Please let me know. Thank you.
Upvotes: 0
Views: 1570
Reputation: 1953
Use Assembly.LoadFrom
to load the assembly into memory, then you can use Activator.CreateInstance
to create an instance of your preferred type. You need to user reflection for this:
Assembly assembly = Assembly.LoadFrom("c:\\path\\MyDll.dll");
Type type = assembly.GetType("MyClass");
object instanceOfMyType = Activator.CreateInstance(type);
Take a look on reflection in order to create instances with parameters.
Upvotes: 2
Reputation: 70671
Why do you want to set CopyLocal
to "No"? The usual way to avoid "DLL hell" (aka "deployment nightmare") is to ensure that DLL dependencies are copied into the same directory with your program. IMHO, this is the simplest, most straightforward way to guarantee you are loading the DLL you want.
Note also that if you sign the DLL, install it in the GAC, and then in your own program require a specific version (or a minimum version, depending on your needs), that should also address the "DLL hell" scenarios. I.e. the presence of other versions of the DLL won't conflict, because you've required a specific version and .NET can reliably distinguish the correct version from an incorrect one.
Barring those approaches...
It's not clear what your exact requirements are. However, if you are trying to provide a way to identify an assembly that's not in the usual assembly-loading paths, there are at least a couple of mechanisms you can use.
One way is to use ApplicationBase
and PrivateBinPath
to control how .NET searches for your assemblies.
Another way is to handle the System.AppDomain.AssemblyResolve
event.
That event will be raised any time .NET tries to load a referenced assembly and can't find it. Your handler can then perform whatever search it needs to (or just use a fixed path for that matter), load the assembly itself (e.g. using Assembly.LoadFrom()
), and then return that via the event's arguments object.
Note that the AssemblyResolve
event is only raised if .NET can't find a DLL to load. So that would not be an appropriate solution if it's not tolerable to have a different instance of the DLL that satisfies the reference requirements for the program of that DLL.
Upvotes: 2