This article will show how to make a DLL that contains WPF User Controls and then we can load that .dll using MEF (lazy loading) then how to add that User Controls to other applications from the dll.
DescriptionHi every one, this article will show how to make a DLL that contains WPF User Controls and then we can load that .dll using MEF (lazy loading) then how to add that User Controls to other applications from the dll.It is a very simple demo so I have just used 1 user control in 1 class Library; you can use many or you can use your plug-in as per your requirements.I have read many articles but no one has show this with a perfect example so I have written this article with an example.To do this, we need to do a couple of things:
STEP 1Use the Class Library and add the Interface that will be implemented in the exported class.1.1: In VS2012 add a new project, then add the new class library named "Contract.InheritedContract". 1.2: Add the new interface in it named "IMain".1.3: Now it looks like this:1.4: In "IMain" we will have one string property named "NameOFUC", the name of the User Control.
public interface IMain
{
string NameOFUC { get; }
}
1.5: Add a reference for "system.componentModel.Composition" to the project.1.6: Write "[InheritedExport(typeof(IMain))]" on the Interface. That will export all the classes that inherit this Interface.Now your contract is ready so you just need to inherit the Interface in every class.STEP 2Add the Class Library and add a WPF User Control in it and implement the interface.2.1: In VS2012 add a new project, then add a new class library as shown in step 1.1.Add a new Class Library named "DllWithUC" that contains the User Control or your plug-in.2.2 Add the WPF User Control in it.And then add the reference for the class library that has the interface in it. And add the reference for "System.XAML" to it.Also add the reference of the "system.componentModel.Composition.dll" as shown in Step 1.5.2.3 Implement the "IMain" Interface on the User Control.Step 3Use a new WPF Application in which we will use the MEF to load the .dll and get the exported classes.3.1 Add the WPF Application to the project.Add the WPF Application to the project that will be used to add the Plug-in or User Control in it.3.2 Add a reference for "system.componentModel.Composition" and "Contract.InheritedContract".3.3 Add the "[ImportMany(typeof(IMain))]".To get the imported classes we need to write an import statement like this:It will contain the imported classes collection.3.4 Create a directory catalog to get the .dll files and parts from the .dll.ConclusionUsing MEF and a clean implementation of MVVM in a WPF application you can do amazing things.
Pro WPF: Windows Presentation Foundation in .NET 3.0