问题描述
我的项目是我们在其中加载各种组件并对其执行操作的应用程序。
My project is an application in which we load various assemblies and perform operations on them.
我们都停留在一个情况下,我们需要添加一个引用到我们加载程序集(这将是由用户选择)。所以,我需要添加一个引用的DLL在运行时。
We are stuck at a situation where we need to add a reference to the assembly we load (which will be selected by user). So I need to add a reference to the DLL at run time.
我想本网站,但在这里,他们只支持微软的DLL像System.Security程序等。我想添加一个引用到用户创建DLL(类库)。
I tried this site but here they support only microsoft DLLs like System.Security etc. I want to add a reference to a user created dll (class library).
推荐答案
您不能添加引用在运行时 - 但你可以加载组件 - Assembly.LoadFrom
/ Assembly.LoadFile
等的问题是,你不能的卸载的它们,除非你使用的AppDomain
秒。一旦你有一个组装
,您可以使用 assemblyInstance.GetType(fullyQualifiedTypeName)
以创建通过反射实例(可以然后转换为已知接口等)。
You can't "add a reference" at runtime - but you can load assemblies - Assembly.LoadFrom
/ Assembly.LoadFile
etc. The problem is that you can't unload them unless you use AppDomain
s. Once you have an Assembly
, you can use assemblyInstance.GetType(fullyQualifiedTypeName)
to create instances via reflection (which you can then cast to known interfaces etc).
对于一个简单的例子:
// just a random dll I have locally...
Assembly asm = Assembly.LoadFile(@"d:\protobuf-net.dll");
Type type = asm.GetType("ProtoBuf.ProtoContractAttribute");
object instance = Activator.CreateInstance(type);
在这一点上,我可以投实例
一个已知的基准型/接口,或者继续使用反射来操作它。
At which point I can either cast instance
to a known base-type/interface, or continue to use reflection to manipulate it.
这篇关于装载程序集在运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!