Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

c# - 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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...