在运行时动态更改对dll的引用 [英] Dynamically change the reference to a dll at runtime

查看:96
本文介绍了在运行时动态更改对dll的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一种情况下,我在不同的文件夹中有多个.dll文件,它们都具有相同的名称,其中包含相同的功能(具有相同的名称),但是具有相同名称的功能内部的代码是不同的.

我已经在设计中创建了我的应用程序,引用了这些.dll文件之一.但是我希望在我的应用程序启动时,使用选择用例能够将对这些dll的引用更改为一个.

这可能吗?

谢谢!

解决方案

您不能这样做,如果要使用在运行时选择的dll,则需要先在项目中不直接引用它((在运行时无法更改),然后使用Assembly.Load将其手动加载到您的appdomain中,并对其进行反思以使用其类型(因为您在编译时不知道类型,因为未引用它,因此您必须进行编程针对您查询的类型).

因此,如果您已经针对引用的dll进行了编程,则说明您做错了,因为如果需要动态代码,则内部使用代码的整个方式会有所不同.

例如,如果您在名为"mydll.dll"的dll中使用方法"mymethod"使用类型"mytype"(如果您使用它引用它的话,则很简单)

  new mytype().mymethod(); 

如果您不是在引用dll,而是动态解析它,则看起来像是

  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); 

我们还需要知道您要实现的目标,有一些方法可以使此过程更简单,但这取决于您的用例(例如,在插件系统中,您需要声明该插件的接口并共享该dll并直接引用它,仅动态加载插件,因此您可以将实例直接转换为该接口,而不必动态调用方法)

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 !

解决方案

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)

这篇关于在运行时动态更改对dll的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆