且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何引用在运行时DLL?

更新时间:2022-12-30 15:02:26

我实现了像你所要求的,通过在一个给定的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.