Leo Vo
Leo Vo

Reputation: 10330

The way to create a plug-in application

I have a .NET WinForm application. I want when my application run, it will detect a DLL. If this DLL exists, my app will load and use it like a built-in DLL.

Please help me some examples. Thanks.

Upvotes: 2

Views: 180

Answers (4)

TomTom
TomTom

Reputation: 62093

Read up on MEF - Microsoft Extensibility Framework, in the System.ComponentModel.Composition namespace. Part of the core .NET 4.0 functionality.

Upvotes: 4

JohnD
JohnD

Reputation: 14747

If you are looking for something simple using reflection, you could take the approach of loading the type information from the config file:

public interface IMyPlugin
{
    void DoSomethingPlugInIsh();
}

class Program
{
    static void Main(string[] args)
    {
        IMyPlugin plugin1 = CreateFromConfig<IMyPlugin>("PluginType");
        plugin1.DoSomethingPlugInIsh();

        // etc...
    }

    static T CreateFromConfig<T>(string typeSettingName)
        where T : class
    {
        string typeName = ConfigurationManager.AppSettings[typeSettingName];
        if (string.IsNullOrEmpty(typeName))
            return null;

        var type = Type.GetType(typeName);
        return (T)Activator.CreateInstance(type);
    }

}

The config file would contain the information about the type you are going to instantiate, so people could change it to their own plugin:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <appSettings>
    <add key="PluginType" value="TestPlugin.MyClass, TestPlugin, Version=1.0.0.0, Culture=neutral" />
  </appSettings>
</configuration>

And the class would reference your interface and implement it:

public class MyClass : IMyPlugin
{
    public void DoSomethingPlugInIsh()
    {
        Console.WriteLine("Hello there");
    }
}

Hope that helps,

John

Upvotes: 1

Sascha Hennen
Sascha Hennen

Reputation: 73

You can also use the Microsoft Add-In Framework (MAF) using System.Addin Namespace.

Read more on http://msdn.microsoft.com/en-us/library/bb384200.aspx

Upvotes: 3

Deanna
Deanna

Reputation: 24253

If it's just one DLL, add a reference to it and catch any exceptions using it. If there can be many (maybe 3rd party) DLL, use one of the Assembly.Load* methods and you can then enumerate classes from the Assembly object.

See some examples in my BuilderPro project, specifically Extensions.cs and Extension.cs.

Upvotes: 1

Related Questions