How to reference a DLL on runtime? How to reference a DLL on runtime? wpf wpf

How to reference a DLL on runtime?


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.


Have a look at MEF. it should provide exactly what you are looking for.

Using reflection is also an option, but MEF will be a better choice if you ask me.


I think you can start of with something like

Assembly assembly = Assembly.LoadFrom("Something.dll");Type type = assembly.GetType("SomeType");object instanceOfSomeType = Activator.CreateInstance(type);

Then you can use it