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

查看:27
本文介绍了如何在运行时引用 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).

任何想法如何在运行时引用 dll?有什么更好的想法来实现吗?

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天全站免登陆