Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load plugins in .NET?

I'd like to provide some way of creating dynamically loadable plugins in my software. Typical way to do this is using the LoadLibrary WinAPI function to load a dll and calling GetProcAddress to get an pointer to a function inside that dll.

My question is how do I dynamically load a plugin in C#/.Net application?

like image 326
Michał Piaskowski Avatar asked Aug 18 '08 07:08

Michał Piaskowski


People also ask

What are .NET plugins?

The plugin framework is a NuGet package that allows you to customise and extend a . NET application at runtime. Code examples are provided for ASP.NET Core, Blazor, Console Apps and WPF & WinForms. The plugin framework package can be installed from NuGet and also supports the delivery of plugins from NuGet.

What are plugins in C#?

Introduction. In today's article, we will take a look at using the plugin pattern in C#. The plugin pattern allows us to drop assemblies into a particular location and use their implementation in our applications. This is one way we can create loosely coupled applications.

How do I load a net project in Visual Studio?

Right-click Solution 'QuickSolution' in Solution Explorer, and select Add > New Project from the context menu. On the Add a new project page, type empty into the search box at the top, and select C# under All languages. Select the C# Empty Project (. NET Framework) template, and then select Next.

What is plugin in ASP NET MVC?

The ASP.NET MVC plugins is actually a extension based on another plugin framework OSGi.NET, technically, you can replace it with any other frameworks like MEF, Sharp-develop with some wrapping.


2 Answers

As of .NET 3.5 there's a formalized, baked-in way to create and load plugins from a .NET application. It's all in the System.AddIn namespace. For more information you can check out this article on MSDN: Add-ins and Extensibility

like image 125
Matt Hamilton Avatar answered Oct 09 '22 07:10

Matt Hamilton


The following code snippet (C#) constructs an instance of any concrete classes derived from Base found in class libraries (*.dll) in the application path and stores them in a list.

using System.IO; using System.Reflection;  List<Base> objects = new List<Base>(); DirectoryInfo dir = new DirectoryInfo(Application.StartupPath);  foreach (FileInfo file in dir.GetFiles("*.dll")) {     Assembly assembly = Assembly.LoadFrom(file.FullName);     foreach (Type type in assembly.GetTypes())     {         if (type.IsSubclassOf(typeof(Base)) && type.IsAbstract == false)         {             Base b = type.InvokeMember(null,                                        BindingFlags.CreateInstance,                                        null, null, null) as Base;             objects.Add(b);         }     } } 

Edit: The classes referred to by Matt are probably a better option in .NET 3.5.

like image 44
Zooba Avatar answered Oct 09 '22 08:10

Zooba