如何引用在运行时DLL? [英] How to reference a DLL on runtime?

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

问题描述

我建立与WPF和C#应用程序,基本上我想允许任何人创建一个DLL,放入(类似插件)的文件夹。该应用程序将所有的DLL文件夹上,加载它们用自己的方法(在接口上定义)。

I'm building an application with WPF and C#, basically I want to allow anyone to create a dll and put it into a folder (similar to plugins). The application will take all the dlls on the folder, load them and use their methods (defined on an interface).

任何想法如何引用在运行时动态链接库?任何更好的想法如何实现这一点?

Any ideas how to reference the dlls on runtime? Any better idea how to implement this?

推荐答案

我实现了像你所要求的,通过在一个给定的DLL搜索目录,并发现实现特定接口的类。下面是我用来做这个类:

I've implemented something like you are asking for that searches through dlls in a given directory and finds classes that implement a particular interface. Below is the class I used to do this:

public class PlugInFactory<T>
{
    public T CreatePlugin(string path)
    {
        foreach (string file in Directory.GetFiles(path, "*.dll"))
        {
            foreach (Type assemblyType in Assembly.LoadFrom(file).GetTypes())
            {
                Type interfaceType = assemblyType.GetInterface(typeof(T).FullName);

                if (interfaceType != null)
                {
                    return (T)Activator.CreateInstance(assemblyType);
                }
            }
        }

        return default(T);
    }
}



所有你所要做的就是初始化这个类的东西像这样的:

All you have to do is initialize this class with something like this:

   PlugInFactory<InterfaceToSearchFor> loader = new PlugInFactory<InterfaceToSearchFor>();
     InterfaceToSearchFor instanceOfInterface = loader.CreatePlugin(AppDomain.CurrentDomain.BaseDirectory);

如果这个答案或任何其他的答案的帮助你解决你的问题,请把它标记为答案通过点击对号。此外,如果你觉得这是一个很好的解决方案给予好评它来表达你的谢意。只是想我会提到它,因为它并不像你接受了你的任何其他问题的答案。

If this answer or any of the other answers help you in solving your problem please mark it as the answer by clicking the checkmark. Also if you feel like it's a good solution upvote it to show your appreciation. Just thought I'd mention it since it doesn't look like you accepted answers on any of your other questions.

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

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