Entity
Entity

Reputation: 8222

C# create DLL Plugin that implements interface

I'm writing a simple plugin based program. I have an interface IPlugin which has some methods and functions, and a List<Plugin> in my main program. For the sake of simplicity, lets say its defined like this:

public interface IPlugin
{
    public void OnKeyPressed(char key);
}

Everytime a key is pressed, I loop through the Plugin list, and call OnKeyPressed(c) on each of them.

I can create a class like so, and add it to the list...

public class PrintPlugin
{
    public void OnKeyPressed(char key)
    {
        Console.WriteLine(c);
    }
}

And then whenever you press a key, its printed out. But I want to be able to load plugins from DLL files. This link was helpful, but it doesn't explain how to have the classes in the DLL implement my IPlugin interface... How can I do that? I really don't want to have to copy the IPlugin.cs file every time I want to make a plugin...

Upvotes: 6

Views: 12844

Answers (3)

platon
platon

Reputation: 5340

If you need to load user defined plugins, you should search for new DLLs when the application starts (or any other action). This can be done by using:

1) AppDomain.CurrentDomain.GetAssemblies() method returns the list of loaded assemblies in the current AppDomain

2) Search all DLLs in a folder where plugins should be positioned and check if a certain assembly is in the list. If not, use the Assembly.Load method to load this assembly, find the IPlugin class in it and finally add it to the List object.

Upvotes: 0

Steven Behnke
Steven Behnke

Reputation: 3344

You may want to look into the Managed Extensibility Framework as well. It provide a complete API for writing plugin based programs and covers a lot of concerns such as security if you're ever going to plan to make the plugin API available to third parties.

Upvotes: 2

deepee1
deepee1

Reputation: 13226

If I am understanding you correctly...

Create 3 Projects:

Project 1: Your main program (the one with List in it)

Project 2: the project with your interface

public interface IPlugin
{
public void OnKeyPressed(char key);
}

Project 3: A sample Plugin

public class PrintPlugin : IPlugin
{
public void OnKeyPressed(char key)
{
    Console.WriteLine(c);
}
}

Then Add project 2 as a reference to both project 1 and 3.

This way you share the interface with both your main project and any of your plugins.

I have used this on a couple of projects and it has served me well.

Upvotes: 7

Related Questions