Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# create DLL Plugin that implements interface

Tags:

c#

dll

load

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...

like image 586
Entity Avatar asked Jul 18 '11 19:07

Entity


2 Answers

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.

like image 171
deepee1 Avatar answered Sep 22 '22 01:09

deepee1


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.

like image 30
Steven Behnke Avatar answered Sep 18 '22 01:09

Steven Behnke