Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a DLL on runtime?

Tags:

c#

plugins

wpf

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?

like image 983
HoBa Avatar asked Apr 22 '11 02:04

HoBa


2 Answers

I am working on something similar, where a customer may have different versions of a third-party DLL installed, though the name and location are the same. If we don't reference the right version, we get failures. I am using reflection to identify the version, but I need to either modify the setup to use a different DAL class depending on the version, or make the DAL version independent through an interface.

I am leaning toward the second. If you make a "dummy DLL in your code that implements an interface that has all the methods you want to invoke from the target assembly, and pass in not the actual type as a parameter but the interface, then you should be able to use all the methods in your design-time code and compile based on your mock-up implementations, and even do your testing, but then when you load the actual assembly at runtime get the results from the real assembly. Let me know if this works for you, and I will let you know as well.

Joey Morgan

like image 118
Joseph Morgan Avatar answered Oct 03 '22 04:10

Joseph Morgan


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.

like image 28
2 revs, 2 users 85% Avatar answered Oct 03 '22 03:10

2 revs, 2 users 85%