SOLID design principles using MEF in Silverlight and WPF

In this part of the Silverlight refactoring series we will be looking at two ways the Managed Extensibility Framework (MEF) can help you refactor Silverlight or WPF applications to follow SOLID design principles.

The code used in this post can be downloaded here.

Apart from saying

through discovery and composition MEF gives you the ability to build applications which will be flexible enough for your every need

I won’t be covering what MEF is or how it works in depth in this post. Instead I recommend checking out the following blogs as well as the MEF site on Codeplex for some great tutorials.

What problem does MEF solve in this application?

The code below shows the Calculate method in the ViewModel.

public void  Calculate()
{
    Calculator calculator = new Calculator();
    Result = calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}

Notice how Calculator class is created and used within the method. This means there’s no way of changing what class is used for calculations without modifying the code in the ViewModel.

In other words the calculator is tightly coupled to the ViewModel.

Composing, Initializing, Setting up, Bootstrapping, Configuring or whatever you want to call it in MEF

MEF works by using a catalog to discover extensions within assemblies. As the assemblies used in this application are in same XAP we can call the CompositionInitializer SatisfyImports method to automatically configure a container and compose the parts within it.

Looking at the class diagram for the application

Silverlight Class Diagram

we could decide

  • only the Calculator class will be an composable part
  • the ViewModel and the Calculator will be composable parts
  • the CalculatorPage, ViewModel and the class should all be composable parts

As this application only contains a single page we will go with the second option. This means we will be calling the CompositionInitializer SatisfyImport method in the CalculatorPage constructor as shown below

public CalculatorPage()
{
    InitializeComponent();
    CompositionInitializer.SatisfyImports(this);            
}

Adding MEF Export Attributes

An export attribute is used to make classes and properties discoverable to the catalog and composable by the container.

As the Calculator class is used by the ViewModel we need to add an Export attribute to it. Because the Calculator implements the ICalculator interface we can use this as the contract type.

[Export(typeof(ICalculator))]
public class Calculator : ICalculator
{
public int Add(int firstValue, int secondValue)
{
    return firstValue + secondValue;
}
}

Similarly as the ViewModel is used by the CalculatorPage it also needs to be decorated with an Export attribute. As no contract is specified, MEF will use the fully qualified name of the type as the contract.

[Export]
public class CalculatorViewModel : INotifyPropertyChanged
{
    .....
}

An important thing to remember is that the export attribute is not allowed on the instance passed to SatisfyImports otherwise you will see the error below

MEF Export Error

Using MEF Property Imports

To use property imports in MEF we need to add a Calculator property to the ViewModel add decorate it with an Import attribute. In Silverlight MEF requires the property to be public.

[Import]
public ICalculator Calculator { get; set; }

The Calculate method in the ViewModel uses the property like this

public void Calculate()
{
    Result = Calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}

In the code behind of the CalculatorPage we need to add a CalculatorViewModel property, decorate it with an Import attribute and set it as the data context.

public partial class CalculatorPage : UserControl
{
    [Import]
    public CalculatorViewModel CalculatorViewModel { get; set; }

    public CalculatorPage()
    {
        InitializeComponent();
        CompositionInitializer.SatisfyImports(this);
        DataContext = CalculatorViewModel;
    }
}

If we run the application as it is MEF composes all the parts of the application and we are able to add numbers together… which is good but not great because I don’t recommend you should build applications only using property imports.

Using MEF Constructor Imports

I always try to follow the SOLID design principles whenever I’m developing applications.

The D in SOLID design principles stands for Dependency Inversion Principle.

One of the first things you should be taught when learning test driven development or even good coding practices is how SOLID design principles will help you create applications that are easier to develop, configure, maintain and unit test.

See my blog post ‘How to write better unit tests using RhinoMocks and stubs‘ for an example.

The good news is MEF supports constructor imports.

Using the ImportingConstructor attribute the CalculatorViewModel now takes in a Calculator in its constructor as shown below

[ImportingConstructor]
public CalculatorViewModel(ICalculator calculator)        
{     
    _calculator = calculator;        
    ...
}

and the calculate method uses the calculator like this

public void Calculate()
{
    Result = _calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}

Take care not to over engineer

So what about the importing the ViewModel in the CalculatorPage? We could stick to using a property for the ViewModel or pass it in the ViewModel constructor (in which case the call to CompositionInitializer SatisfyImports method will have to done in the App.xaml code behind).

I would be inclined to leave it as it is. Because we want to be able to unit test the ViewModel it makes sense to use importing constructors so we stub out the calculator.

Are we ever going to unit test the CalculatorPage? Probably not, and if we do need to, it’s not a major refactoring task.

In any case thanks to MEF the ViewModel can be changed without modifying the code behind for the CalculatorPage.

So what have we achieved?

By using SOLID design principles and MEF we have managed to remove the tight coupling between the ViewModel and the Calculator.

There is a lot of discussion about what MEF is in the development community. Despite numerous claims and comments that it’s not a dependency injection framework, I can’t help thinking it takes a step closer to being one with each release.

The last thing I’ll say about MEF is that

the number of options you have of using MEF is either impressive or confusing depending on what side of the fence you sit on

If you have arrived here from a search engine, this post is part of series about refactoring Silverlight applications.

So if you’re thinking, what if there’s an exception converting a string into an integer, check out the post ‘Validation in Silverlight and WPF using ValidatesOnExceptions‘ which shows one approach in solving this problem using exceptions.

Comments