How to reference a DLL on runtime?

后端 未结 6 954
有刺的猬
有刺的猬 2020-12-08 23:43

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 t

6条回答
  •  醉梦人生
    2020-12-09 00:29

    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
    {
        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 loader = new PlugInFactory();
         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.

提交回复
热议问题