Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change the reference to a dll at runtime

I have a situation where I have several .dll files in different folders , all with the same name , that contains the same functions ( with the same names ) , but the code inside functions with the same name is different.

I have created my application in design , referencing one of these .dll files. But I want that when my application start , using a select case to be able to change the reference to one of these dll.

Is this possible ?

Thank you !

like image 692
alex Avatar asked May 22 '26 18:05

alex


1 Answers

You can't do that, if you want to use a dll that you select at runtime, you need to start by NOT referencing it directly in your project (that can't be changed at runtime) then manually loading it in your appdomain using Assembly.Load and reflect upon it to use it's types (as you don't know the types at compile time as it's not referenced, so you have to program it against types you query).

So if you already programmed against the referenced dll, you did it wrong, as the whole way of using the code Inside it is diferent if you need it to be dynamic.

For example if you have a type "mytype" with a method "mymethod" in a dll named "mydll.dll" if you reference it using it is as simple as doing

new mytype().mymethod();

If you're not referencing the dll but resolving it dynamically it would look like

var asm = Assembly.Load("mydll.dll");
var type = asm.DefinedTypes.Single(t=>t.Name == "mytype");
var instance = Activator.CreateInstance(type);
var methodinfo = type.GetMethod("mymethod");
methodinfo.Invoke(instance);

Also we need to know what you're trying to achieve, there are ways to make this a bit simpler but it depends on your use case (in a plugin system for example you'd declare an interface for the plugin and share that dll and reference it directly, only loading the plugins dynamically, so you could directly cast instance to that interface and not have to invoke methods dynamically)

like image 126
Ronan Thibaudau Avatar answered May 25 '26 09:05

Ronan Thibaudau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!