In my previous post I created a contracts assembly that will define the contracts used by MEF in our solution. In this post, I’ll create some core objects, namely the ViewModel, and wire it up to starting importing extensions via MEF.
We’ll start by added a new class library project named Customer.Core to our solution:
I’ll then delete the default Class1.cs file that gets created. A common practice I follow when using the MVVM is to create an abstract base class for my ViewModels. In this create I’ll create a class named ViewModelBase. Here’s what it looks like:
Next, I’ll add a couple of references. This first is to the Customer.Contracts project I created in the last post. I’ll then add a reference to System.ComponentModelComposition. This is a key assembly as it contains the various attributes, catalogs, and containers you’ll need when working with MEF. I’m now ready to add my CustomerViewModel and CustomerListViewModel classes. Here’s what I ended up with:
There are a couple of things I want to call out on the implementation of the CustomerListViewModel. First, is the Repository property here’s what it looks like:
Notice the Import attribute? This tell MEF that I’ll be populating the property via an import and that the import will be of type ICustomerRepository, which I defined in the Customer.Contracts assembly.
Second, we should look at the implementation of the GetCustomers method:
Lines 62, 63, and 65 are key here. In line 62 I’m creating an AssemblyCatalog, this is the assembly that will contain the implementation of the ICustomerRepository class. In line 63 I created a CompositionContainer that will be responsible for performing the necessary imports from the AssemblyCatalog. Line 65 tells the CompositionContainer to perform the import using the current class, which means the CompositionContainer will populate the Repository property.
You can download the source code here. Of course, I’m missing one key piece of functionality, exports! In my next post I’ll use MEF to export a test repository and then write some unit tests that consume that repository.