I always asked myself how the Plugins work. So I read some articles about it, and found some really interesting ideas. I’ve found the following way for implementing plugins, it does not mean that it’s the only one, but you can research more if this approach does not work for you.
When do I need to implement a plugin?
I can think in some scenarios such as:
- When the business rules change often and you don’t want to recompile the whole application for an udpate. (You can solve this by developing with layers, and others techniques).
- In order to give the chance to thrid party for implementing functionally in your application.
So, What do I need for a plugin?
Easy, you need 3 key parts:
- Contract definition: This part of you application is in charge of expose all the tasks that the plugin has to implement, and also exposes the application’s resources that the plug in allowed to access.
- Contract implementation: The final implementation of tasks.
- Plugin loader: This part of you application is going to load all the files related to the application. The final result is to have a way to access all the loaded plugins and its members.
Sounds easy right? In fact, it’s easy, the only thing is how you could implement each step in you favorite language.
I have implemented a simple loader by using C# 3.0, LINQ and Generics. I based my example on a article that I found in Internet, however I added the Generics and LINQ in order to take advantage of .NET 3.5.
Step 1: Plugin contract.
In C# the most common way for defining a contract is by using a Interface. So, we only need to create a project that is going to store all the interfaces that plug in has to implement, and the resources that are shared among the plug in and the application.
Step 2: Plugin Implementation
Now, we have to create a class that implements (which means write the functionality) for the contracts of the previous step.
Step 3: Plugin loaders
Here is the tricky part of this, our application is going to load binary files. Those files are going to be incorpored to our running application. After that, we should be able to call (if required) a particular task from a plugin. In order to do this in C#, we use ‘late binding’ concept, that .NET includes. It allows our application for loading assemblies in runtime. Also by using reflextion we can generate instances of our loaded assemblies.
Here is a screenshot of my sample in C#:
So, I’m attaching the related code as an example of how you could implement a plug in loader.
Also you can check some really nice articles: