Introduction
MEF is a managed extensibility framework. It's a light-weight framework to build a plugin solution. At the base level, MEF will use reflection. Before reading this article, I would recommend reading the following article,
Simple Plugin Architecture Using Reflection. This article is about creating plugin architecture using reflection. In the current article, I am using the same example, but here we build a plugin solution with MEF framework.
Why MEF?
In normal reflection, we need to explicitly mention which type of object required so it will have explicit registration. With a complete assembly, we need to load in an application to find the required contract. However, in MEFm we have implicit parts with declarative syntax called “Import”/"ImportMany" and “Export”. The MEF composite engine will take the responsibility of satisfying its imports with its respective available’ s from other parts.
The most important thing is MEF will find its import and export by its metadata. Here it will not load the assemblies. MEF will suggest creating Lazy objects for export types. In that case, MEF will not instantiate export types until the time comes for usage. MEF will allow reusability through the application.
We will take the example of building a calculator application for it.
Create a project of type Class Library and name it as Plugger. It will be responsible for connecting our main calculator application to the sub-libraries of the calculator.
In this project, we will add an interface with the name IPlugger, as shown below:
- using System.Windows.Controls;
-
- namespace MEF.Sample.Plugger.Contract
- {
- public interface IPlugger
- {
-
-
-
- string PluggerName { get; set; }
-
-
-
-
-
- UserControl GetPlugger();
- }
- }
Now we will create plug board where all plugs will connect to the main application. For this, create a WPF Project and below the code in MainWindow.xaml, add the below code:
- <Window x:Class="MEF.Sample.Calculator.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:local="clr-namespace:MEF.Sample.Calculator"
- WindowStyle="None" ResizeMode="NoResize"
- mc:Ignorable="d" Height="450" Width="800" MouseDown="Window_MouseDown" BorderBrush="Silver" BorderThickness="1" >
- <Window.Resources>
- <Style TargetType="{x:Type TabItem}">
- <Setter Property="FontWeight" Value="Bold" />
- <Setter Property="Background" Value="White" />
- <Setter Property="Foreground" Value="Black" />
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="{x:Type TabItem}">
- <Border BorderThickness="1" BorderBrush="LightGray" x:Name="TabBorder" Background="{TemplateBinding Background}" Margin="3">
- <ContentPresenter ContentSource="Header" Margin="3" />
- </Border>
- <ControlTemplate.Triggers>
- <Trigger Property="IsSelected" Value="True">
- <Setter TargetName="TabBorder" Property="BorderBrush" Value="Purple" />
- </Trigger>
- </ControlTemplate.Triggers>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Style>
- </Window.Resources>
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="30"/>
- <RowDefinition Height="400"/>
- <RowDefinition Height="20"/>
- </Grid.RowDefinitions>
- <Grid Grid.Row="0" Background="Orange">
- <Label Content="Calculator" Foreground="White" FontWeight="Bold"/>
- <Button Name="btnClose" Height="30" Width="30" Content="X" FontWeight="Bold" Foreground="Red" Cursor="Hand" Focusable="False"
- HorizontalAlignment="Right" VerticalAlignment="Bottom" Background="{x:Null}" Margin="0,0,2,0" Click="BtnClose_Click"/>
- </Grid>
- <Grid Grid.Row="1">
- <TabControl Name="tabPlugs">
- </TabControl>
- </Grid>
- <Grid Grid.Row="2" Background="Gray">
-
- </Grid>
- </Grid>
- </Window>
In MainWindow.xaml.cs, add the below code:
- using MEF.Sample.Plugger.Contract;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.Composition;
- using System.ComponentModel.Composition.Hosting;
- using System.Configuration;
- using System.IO;
- using System.Linq;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
-
- namespace MEF.Sample.Calculator
- {
-
-
-
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- LoadView();
- LoadUI();
- }
- private CompositionContainer _container;
-
- [ImportMany(typeof(IPlugger))]
- private IEnumerable<Lazy<IPlugger>> _pluggers;
-
- public void LoadView()
- {
- string plugName = ConfigurationSettings.AppSettings["Plugs"].ToString();
- var connectors = Directory.GetDirectories(plugName);
- var catalog = new AggregateCatalog();
- connectors.ToList().ForEach(connect => catalog.Catalogs.Add(new DirectoryCatalog(connect)));
- _container = new CompositionContainer(catalog);
- _container.ComposeParts(this);
- }
-
-
-
-
- public void LoadUI()
- {
- try
- {
- TabItem buttonA = new TabItem();
- buttonA.Header = "Welcome";
- buttonA.Height = 30;
- buttonA.Content = "You welcome :)";
- tabPlugs.Items.Add(buttonA);
-
- foreach (Lazy<IPlugger> plug in _pluggers)
- {
- TabItem button = new TabItem
- {
- Header = plug?.Value?.PluggerName,
- Height = 30,
- Content = plug?.Value?.GetPlugger()
- };
- tabPlugs.Items.Add(button);
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "Internal Error", MessageBoxButton.OK, MessageBoxImage.Error);
- }
-
- }
-
- private void BtnClose_Click(object sender, RoutedEventArgs e)
- {
- Close();
- }
-
- private void Window_MouseDown(object sender, MouseButtonEventArgs e)
- {
- if (e.ChangedButton == MouseButton.Left)
- this.DragMove();
- }
-
-
- }
- }
In App.Config add key to access the PlugBoard Folder. The PlugBoard is the folder were all calculator libraries will be placed.
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" />
- </startup>
- <appSettings>
- <add key="Plugs" value="Path of PlugBoard Folder\PlugBoard\"/>
- </appSettings>
- </configuration>
To implement the MEF solution, we need the below two references:
- System.ComponentModel.Composition
- System.ComponentModel.Composition.Hosting
In the above MainWindow.xaml.cs class, we can see that the method LoadView where we are reading files is available in the PlugBoard folder and adding in the container. The container will take all export providers. With this movement from the export keyword, MEF learns which class it has to load (lazily) in the main application. From Import/ImportMany, MEF will identify which variable it has to map the exported values.
This is the first snap of the Main window:
Now it is time to create plugs for the Calculator plugboard. Create a project of type class library. We will name it “MEF.RegularCalculator”.
Delete Class1.cs and create the View folder
Add a WPF UserControl to it with the name RegularView
Add Plugger Project as a reference to this project
Add the below assemblies as a reference;
- System.ComponentModel.Composition
- System.ComponentModel.Composition.Hosting
In RegularView.xaml.cs, for the RegularView class, inherit the interface IPlugger and provide implementation as below:
- using MEF.Sample.Plugger.Contract;
- using System.ComponentModel.Composition;
- using System.Text.RegularExpressions;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
-
- namespace MEF.RegularCalculator.View
- {
-
-
-
- [Export(typeof(IPlugger))]
- public partial class RegularView : UserControl, IPlugger
- {
- public RegularView()
- {
- InitializeComponent();
- }
-
-
-
-
- public string PluggerName { get; set; } = "Regular";
-
-
-
-
-
- public UserControl GetPlugger() => this;
-
- private void BtnAdd_Click(object sender, RoutedEventArgs e)
- {
- lblRes.Content = int.Parse(txtA.Text) + int.Parse(txtB.Text);
- }
-
- private void BtnSubstract_Click(object sender, RoutedEventArgs e)
- {
- lblRes.Content = int.Parse(txtA.Text) - int.Parse(txtB.Text);
- }
-
- private void BtnMultiply_Click(object sender, RoutedEventArgs e)
- {
- lblRes.Content = int.Parse(txtA.Text) * int.Parse(txtB.Text);
- }
-
- private void BtnDivide_Click(object sender, RoutedEventArgs e)
- {
- lblRes.Content = int.Parse(txtA.Text) / int.Parse(txtB.Text);
- }
-
- private void AllowOnlyNumbers(object sender, TextCompositionEventArgs e)
- {
- Regex regex = new Regex("[^0-9]+");
- e.Handled = regex.IsMatch(e.Text);
- }
-
- }
- }
We are implementing IPlugger here because when we load the Main Calculator application, the main application looks for the class which is being mentioned as Export. It gets the plugger name by the property PluggerName and loads the User controls on the main app using the method GetPlugger().
Now go to Project Properties -> Build and change the Output to PlugBoard folder. As we discussed earlier, PlugBoard is the folder where we are placing all our assemblies DLLs. In the main application, App.Config, we are configuring the path of the PlugBoard.
Build the entire solution and the “MEF.Sample.Calculator” project set as a startup project. Run the application, below is the output snap of window. Here you can see “Regular” is added:
Now we will follow by creating projects with the names “MEF.TableCalculator” and “MEF.TrigonometryCalculator”. Below is the output snap of window where you can now see 2 more options plugged to the main calculator application with the names “Table Calci” and “Trigonometry”
For your reference, the Project Solution is uploaded and you can download it. Before running the project, remember to configure the PlugBoard folder path in App.Config.
This is how we can just keep on adding the required plugs and build the project so it will be available for usage. After delivering to the customer, if the customer requires more options, we can keep on extending the calculator functionalities without touching the previous code. So basically, it will obey the Open/Closed Principle of solid principles (i.e. open for extension closed for modification.)
Summary
In this article, we have seen how we can develop a plug and play solution to meet our requirements which need extensibility using MEF Framework