Use Extension method to write cleaner code

This blog post will show you step by step to refactoring some code to be more readable (at least what I think). Patrik Löwnedahl gave me some of the ideas when we where talking about making code much cleaner.


The following is an simple application that will have a list of movies (Normal and Transfer). The task of the application is to calculate the total sum of each movie and also display the price of each movie.

class Program
{
enum MovieType
{
Normal,
Transfer
}

static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfNormalMovie = 0;
int totalPriceOfTransferMovie = 0;

foreach (var movie in movies)
{
if (movie == MovieType.Normal)
{
totalPriceOfNormalMovie += 2;
Console.WriteLine(“$2”);
}
else if (movie == MovieType.Transfer)
{
totalPriceOfTransferMovie += 3;
Console.WriteLine(“$3”);
}
}
}

private static IEnumerable<MovieType> GetMovies()
{
return new List<MovieType>()
{
MovieType.Normal,
MovieType.Transfer,
MovieType.Normal
};
}
}


In the code above I’m using an enum, a good way to add types (isn’t it ;)). I also use one foreach loop to calculate the price, the loop has a condition statement to check what kind of movie is added to the list of movies. I want to reuse the foreach only to increase performance and let it do two things (isn’t that smart of me?! ;)).


First of all I can admit, I’m not a big fan of enum. Enum often results in ugly condition statements and can be hard to maintain (if a new type is added we need to check all the code in our app to see if we use the enum somewhere else). I don’t often care about pre-optimizations when it comes to write code (of course I have performance in mind). I rather prefer to use two foreach to let them do one things instead of two. So based on what I don’t like and Martin Fowler’s Refactoring catalog, I’m going to refactoring this code to what I will call a more elegant and cleaner code.


First of all I’m going to use Split Loop to make sure the foreach will do one thing not two, it will results in two foreach (Don’t care about performance here, if the results will results in bad performance, you can refactoring later, but computers are so fast to day, so iterating through a list is not often so time consuming.)

Note: The foreach actually do four things, will come to is later.

var movies = GetMovies();

int totalPriceOfNormalMovie = 0;
int totalPriceOfTransferMovie = 0;

foreach (var movie in movies)
{
if (movie == MovieType.Normal)
{
totalPriceOfNormalMovie += 2;
Console.WriteLine(“$2”);
}
}

foreach (var movie in movies)
{
if (movie == MovieType.Transfer)
{
totalPriceOfTransferMovie += 3;
Console.WriteLine(“$3”);
}
}


To remove the condition statement we can use the Where extension method added to the IEnumerable<T> and is located in the System.Linq namespace:

foreach (var movie in movies.Where( m => m == MovieType.Normal))
{
totalPriceOfNormalMovie += 2;
Console.WriteLine(“$2”);
}

foreach (var movie in movies.Where( m => m == MovieType.Transfer))
{
totalPriceOfTransferMovie += 3;
Console.WriteLine(“$3”);
}


The above code will still do two things, calculate the total price, and display the price of the movie. I will not take care of it at the moment, instead I will focus on the enum and try to remove them. One way to remove enum is by using the Replace Conditional with Polymorphism. So I will create two classes, one base class called Movie, and one called MovieTransfer. The Movie class will have a property called Price, the Movie will now hold the price:

public class Movie
{
public virtual int Price
{
get { return 2; }
}
}

public class MovieTransfer : Movie
{
public override int Price
{
get { return 3; }
}
}


The following code has no enum and will use the new Movie classes instead:

class Program
{
static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfNormalMovie = 0;
int totalPriceOfTransferMovie = 0;

foreach (var movie in movies.Where( m => !(m is MovieTransfer)))
{
totalPriceOfNormalMovie += movie.Price;
Console.WriteLine(movie.Price);
}

foreach (var movie in movies.Where( m => m is MovieTransfer))
{
totalPriceOfTransferMovie += movie.Price;
Console.WriteLine(movie.Price);
}
}

private static IEnumerable<Movie> GetMovies()
{
return new List<Movie>()
{
new Movie(),
new MovieTransfer(),
new Movie()
};
}
}

If you take a look at the foreach now, you can see it still actually do two things, calculate the price and display the price. We can do some more refactoring here by using the Sum extension method to calculate the total price of the movies:

static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfNormalMovie = movies.Where(m => !(m is MovieTransfer))
.Sum(m => m.Price);

int totalPriceOfTransferMovie = movies.Where(m => m is MovieTransfer)
.Sum(m => m.Price);

foreach (var movie in movies.Where( m => !(m is MovieTransfer)))
Console.WriteLine(movie.Price);

foreach (var movie in movies.Where( m => m is MovieTransfer))
Console.WriteLine(movie.Price);
}


Now when the Movie object will hold the price, there is no need to use two separate foreach to display the price of the movies in the list, so we can use only one instead:

foreach (var movie in movies)
Console.WriteLine(movie.Price);


If we want to increase the Maintainability index we can use the Extract Method to move the Sum of the prices into two separate methods. The name of the method will explain what we are doing:

static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfMovie = TotalPriceOfMovie(movies);

int totalPriceOfTransferMovie = TotalPriceOfMovieTransfer(movies);

foreach (var movie in movies)
Console.WriteLine(movie.Price);

}

private static int TotalPriceOfMovieTransfer(IEnumerable<Movie> movies)
{
return movies.Where(m => m is MovieTransfer)
.Sum(m => m.Price);
}

private static int TotalPriceOfMovie(IEnumerable<Movie> movies)
{
return movies.Where(m => !(m is MovieTransfer))
.Sum(m => m.Price);
}


Now to the last thing, I love the ForEach method of the List<T>, but the IEnumerable<T> doesn’t have it, so I created my own ForEach extension, here is the code of the ForEach extension method:

public static class LoopExtensions
{
public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
{
Contract.Requires(values != null);
Contract.Requires(action != null);

foreach (var v in values)
action(v);
}
}


I will now replace the foreach by using this ForEach method:

static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfMovie = TotalPriceOfMovie(movies);

int totalPriceOfTransferMovie = TotalPriceOfMovieTransfer(movies);

movies.ForEach(m => Console.WriteLine(m.Price));
}


The ForEach on the movies will now display the price of the movie, but maybe we want to display the name of the movie etc, so we can use Extract Method by moving the lamdba expression into a method instead, and let the method explains what we are displaying:


movies.ForEach(DisplayMovieInfo);

private static void DisplayMovieInfo(Movie movie)
{
Console.WriteLine(movie.Price);
}


Now the refactoring is done, or?

EDIT: It’s not done. Niclas Nilsson wrote a good comment that I actually do two things in the TotalPrice… methods, a filtering and a Sum. So both a command and a query. so it will not follow the Command and Query Principle. To make the code more seperated by concerns:

The TotalPriceXXX method are removed and replaced with on called TotalPriceOfMovie. Two properties are added, one for returning the normal movies and one for returning the transfer movies. Here is the result of the new refactoring:

static void Main(string[] args)
{
int totalPriceOfMovie = TotalPriceOfMovie(NormalMovies);

int totalPriceOfTransferMovie = TotalPriceOfMovie(MovieTransfers);

foreach (var movie in movies)
Console.WriteLine(movie.Price);

}

private static int TotalPriceOfMovie(IEnumerable<Movie> movies)
{
return movies.Sum(m => m.Price);
}

private static IEnumerable<Movie> NormalMovies
{
get { return AllMovies.Where(m => !(m is MovieTransfer)); }
}

private static IEnumerable<Movie> MovieTransfers

{
get { return AllMovies.Where(m => m is MovieTransfer); }
}


private static IEnumerable<Movie> AllMovies

{
get { return GetAllMovies(); }
}
private static IEnumerable<Movie> GetMovies()
{
return new List<Movie>()
{
new Movie(),
new MovieTransfer(),
new Movie()
};
}
Note: The GetMovies() method in this code is just a fake method to return fake data, so it could instead be a call to a Repository etc.

I think the new code is much cleaner than the first one, and I love the ForEach extension on the IEnumerable<T>, I can use it for different kind of things, for example:

movies.Where(m => m is Movie)
.ForEach(DoSomething);


By using the Where and ForEach extension method, some if statements can be removed and will make the code much cleaner. But the beauty is in the eye of the beholder. What would you have done different, what do you think will make the first example in the blog post look much cleaner than my results, comments are welcome!

If you want to know when I will publish a new blog post, you can follow me on twitter: http://www.twitter.com/fredrikn

Read More

Use Extension method to write cleaner code

This blog post will show you step by step to refactoring some code to be more readable (at least what I think). Patrik Löwnedahl gave me some of the ideas when we where talking about making code much cleaner.


The following is an simple application that will have a list of movies (Normal and Transfer). The task of the application is to calculate the total sum of each movie and also display the price of each movie.

class Program
{
enum MovieType
{
Normal,
Transfer
}

static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfNormalMovie = 0;
int totalPriceOfTransferMovie = 0;

foreach (var movie in movies)
{
if (movie == MovieType.Normal)
{
totalPriceOfNormalMovie += 2;
Console.WriteLine(“$2”);
}
else if (movie == MovieType.Transfer)
{
totalPriceOfTransferMovie += 3;
Console.WriteLine(“$3”);
}
}
}

private static IEnumerable<MovieType> GetMovies()
{
return new List<MovieType>()
{
MovieType.Normal,
MovieType.Transfer,
MovieType.Normal
};
}
}


In the code above I’m using an enum, a good way to add types (isn’t it ;)). I also use one foreach loop to calculate the price, the loop has a condition statement to check what kind of movie is added to the list of movies. I want to reuse the foreach only to increase performance and let it do two things (isn’t that smart of me?! ;)).


First of all I can admit, I’m not a big fan of enum. Enum often results in ugly condition statements and can be hard to maintain (if a new type is added we need to check all the code in our app to see if we use the enum somewhere else). I don’t often care about pre-optimizations when it comes to write code (of course I have performance in mind). I rather prefer to use two foreach to let them do one things instead of two. So based on what I don’t like and Martin Fowler’s Refactoring catalog, I’m going to refactoring this code to what I will call a more elegant and cleaner code.


First of all I’m going to use Split Loop to make sure the foreach will do one thing not two, it will results in two foreach (Don’t care about performance here, if the results will results in bad performance, you can refactoring later, but computers are so fast to day, so iterating through a list is not often so time consuming.)

Note: The foreach actually do four things, will come to is later.

var movies = GetMovies();

int totalPriceOfNormalMovie = 0;
int totalPriceOfTransferMovie = 0;

foreach (var movie in movies)
{
if (movie == MovieType.Normal)
{
totalPriceOfNormalMovie += 2;
Console.WriteLine(“$2”);
}
}

foreach (var movie in movies)
{
if (movie == MovieType.Transfer)
{
totalPriceOfTransferMovie += 3;
Console.WriteLine(“$3”);
}
}


To remove the condition statement we can use the Where extension method added to the IEnumerable<T> and is located in the System.Linq namespace:

foreach (var movie in movies.Where( m => m == MovieType.Normal))
{
totalPriceOfNormalMovie += 2;
Console.WriteLine(“$2”);
}

foreach (var movie in movies.Where( m => m == MovieType.Transfer))
{
totalPriceOfTransferMovie += 3;
Console.WriteLine(“$3”);
}


The above code will still do two things, calculate the total price, and display the price of the movie. I will not take care of it at the moment, instead I will focus on the enum and try to remove them. One way to remove enum is by using the Replace Conditional with Polymorphism. So I will create two classes, one base class called Movie, and one called MovieTransfer. The Movie class will have a property called Price, the Movie will now hold the price:

public class Movie
{
public virtual int Price
{
get { return 2; }
}
}

public class MovieTransfer : Movie
{
public override int Price
{
get { return 3; }
}
}


The following code has no enum and will use the new Movie classes instead:

class Program
{
static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfNormalMovie = 0;
int totalPriceOfTransferMovie = 0;

foreach (var movie in movies.Where( m => !(m is MovieTransfer)))
{
totalPriceOfNormalMovie += movie.Price;
Console.WriteLine(movie.Price);
}

foreach (var movie in movies.Where( m => m is MovieTransfer))
{
totalPriceOfTransferMovie += movie.Price;
Console.WriteLine(movie.Price);
}
}

private static IEnumerable<Movie> GetMovies()
{
return new List<Movie>()
{
new Movie(),
new MovieTransfer(),
new Movie()
};
}
}

If you take a look at the foreach now, you can see it still actually do two things, calculate the price and display the price. We can do some more refactoring here by using the Sum extension method to calculate the total price of the movies:

static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfNormalMovie = movies.Where(m => !(m is MovieTransfer))
.Sum(m => m.Price);

int totalPriceOfTransferMovie = movies.Where(m => m is MovieTransfer)
.Sum(m => m.Price);

foreach (var movie in movies.Where( m => !(m is MovieTransfer)))
Console.WriteLine(movie.Price);

foreach (var movie in movies.Where( m => m is MovieTransfer))
Console.WriteLine(movie.Price);
}


Now when the Movie object will hold the price, there is no need to use two separate foreach to display the price of the movies in the list, so we can use only one instead:

foreach (var movie in movies)
Console.WriteLine(movie.Price);


If we want to increase the Maintainability index we can use the Extract Method to move the Sum of the prices into two separate methods. The name of the method will explain what we are doing:

static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfMovie = TotalPriceOfMovie(movies);

int totalPriceOfTransferMovie = TotalPriceOfMovieTransfer(movies);

foreach (var movie in movies)
Console.WriteLine(movie.Price);

}

private static int TotalPriceOfMovieTransfer(IEnumerable<Movie> movies)
{
return movies.Where(m => m is MovieTransfer)
.Sum(m => m.Price);
}

private static int TotalPriceOfMovie(IEnumerable<Movie> movies)
{
return movies.Where(m => !(m is MovieTransfer))
.Sum(m => m.Price);
}


Now to the last thing, I love the ForEach method of the List<T>, but the IEnumerable<T> doesn’t have it, so I created my own ForEach extension, here is the code of the ForEach extension method:

public static class LoopExtensions
{
public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
{
Contract.Requires(values != null);
Contract.Requires(action != null);

foreach (var v in values)
action(v);
}
}


I will now replace the foreach by using this ForEach method:

static void Main(string[] args)
{
var movies = GetMovies();

int totalPriceOfMovie = TotalPriceOfMovie(movies);

int totalPriceOfTransferMovie = TotalPriceOfMovieTransfer(movies);

movies.ForEach(m => Console.WriteLine(m.Price));
}


The ForEach on the movies will now display the price of the movie, but maybe we want to display the name of the movie etc, so we can use Extract Method by moving the lamdba expression into a method instead, and let the method explains what we are displaying:


movies.ForEach(DisplayMovieInfo);

private static void DisplayMovieInfo(Movie movie)
{
Console.WriteLine(movie.Price);
}


Now the refactoring is done, or?

EDIT: It’s not done. Niclas Nilsson wrote a good comment that I actually do two things in the TotalPrice… methods, a filtering and a Sum. So both a command and a query. so it will not follow the Command and Query Principle. To make the code more seperated by concerns:

The TotalPriceXXX method are removed and replaced with on called TotalPriceOfMovie. Two properties are added, one for returning the normal movies and one for returning the transfer movies. Here is the result of the new refactoring:

static void Main(string[] args)
{
int totalPriceOfMovie = TotalPriceOfMovie(NormalMovies);

int totalPriceOfTransferMovie = TotalPriceOfMovie(MovieTransfers);

foreach (var movie in movies)
Console.WriteLine(movie.Price);

}

private static int TotalPriceOfMovie(IEnumerable<Movie> movies)
{
return movies.Sum(m => m.Price);
}

private static IEnumerable<Movie> NormalMovies
{
get { return AllMovies.Where(m => !(m is MovieTransfer)); }
}

private static IEnumerable<Movie> MovieTransfers

{
get { return AllMovies.Where(m => m is MovieTransfer); }
}


private static IEnumerable<Movie> AllMovies

{
get { return GetAllMovies(); }
}
private static IEnumerable<Movie> GetMovies()
{
return new List<Movie>()
{
new Movie(),
new MovieTransfer(),
new Movie()
};
}
Note: The GetMovies() method in this code is just a fake method to return fake data, so it could instead be a call to a Repository etc.

I think the new code is much cleaner than the first one, and I love the ForEach extension on the IEnumerable<T>, I can use it for different kind of things, for example:

movies.Where(m => m is Movie)
.ForEach(DoSomething);


By using the Where and ForEach extension method, some if statements can be removed and will make the code much cleaner. But the beauty is in the eye of the beholder. What would you have done different, what do you think will make the first example in the blog post look much cleaner than my results, comments are welcome!

If you want to know when I will publish a new blog post, you can follow me on twitter: http://www.twitter.com/fredrikn

Read More

MVVM, Data Channel, MEF, WCF RIA Services and ViewModel Locator – Silverlight 4.0

In the Aspen project I decided to use a ViewModel locator to find the ViewModel a View should use, I also use MEF for composition of parts. In this post I’m going to write about the MVVM implementation we use in the Aspen project, but first about the Data Channel used in Aspen.

Data Channel

The Aspen project uses WCF RIA Services to do the communication from the client to the server, we decided to use WCF RIA Services because it generates a good “base” for our ViewModel. When writing unit-test when using WCF RIA Services, we “have” to mock the WebDomainClient which is an class passed to the client-side DomainContext constructor. The WebDomainClient will handle the communication with the DomainService. When we write our tests we don’t want to mock the WebDomainClient and we don’t want to have my ViewModel to be dependent on a DomainContext, so instead we use IViewModelDataChannel. An abstraction on top of WCF RIA Services. By using the IViewModelDataChannel we can remove WCF RIA Services and use other frameworks for the communication, for example WCF, WCF Data Services, Web Service etc. Here is an example of a IViewModelDataChannel created for getting the Members stored into Aspen:

<span>public</span> <span>interface</span> IListMemberViewModelDataChannel
{
   <span>void</span> GetAllMembersAsync(Action&lt;IEnumerable&lt;MemberPM&gt;&gt; getAllMembersCompletedCallBack);
}

 

The following is the implementation of the IViewModelDataChannel using WCF RIA Services DomainContext:

[Export(<span>typeof</span>(IListMemberViewModelDataChannel))]
<span>public</span> <span>class</span> ListMemberViewModelDataChannel : IListMemberViewModelDataChannel
{
   MemberDomainContext _memberDomainContext = <span>new</span> MemberDomainContext();

   <span>public</span> <span>void</span> GetAllMembersAsync(Action&lt;IEnumerable&lt;MemberPM&gt;&gt; getAllMembersCompletedCallBack)
   {
      _memberDomainContext.Load&lt;MemberPM&gt;(
               _memberDomainContext.GetMembersQuery(),
               loadOperation =&gt;
              {
                   getAllMembersCompletedCallBack(loadOperation.Entities);
               }
              , <span>null</span>);
   }
}


Note: MEF is used to Export the IViewModelDataChannels and Import them into the ViewModel.

The following is a part of a ViewModel where the IListMemberViewModelDataChannel is used:

[ExportViewModel(<span>&quot;ListMemberViewModel&quot;</span>)]
<span>public</span> <span>class</span> ListMemberViewModel : BaseViewModel, IListMemberViewModel
{
        
 <strong><em><span>private</span> IListMemberViewModelDataChannel _listMemberViewService;</em></strong>

 <span>private</span> IEnumerable&lt;MemberPM&gt; _members = <span>null</span>;
 <span>private</span> MemberPM _selectedMember = <span>null</span>;

 <span>private</span> <span>bool</span> _isBusy = <span>false</span>;

<strong><em> [ImportingConstructor]
 <span>public</span> ListMemberViewModel(IListMemberViewModelDataChannel listMemberViewService)</em></strong>
 {
    Contract.Requires(listMemberViewService != <span>null</span>);
    Contract.Ensures(_listMemberViewService != <span>null</span>);

<strong><em>    <span>this</span>._listMemberViewService = listMemberViewService;</em></strong>

    <span>this</span>.IsBusy = <span>true</span>;
            
    <strong><em><span>this</span>._listMemberViewService.GetAllMembersAsync(GetAllMembersCompleted);</em></strong>
  }

<strong><em>  <span>private</span> <span>void</span> GetAllMembersCompleted(IEnumerable&lt;MemberPM&gt; result)
  {
     <span>this</span>.Members = result;
     <span>this</span>.IsBusy = <span>false</span>;
  }</em></strong>

  <span>public</span> <span>bool</span> IsBusy
  {
     get { <span>return</span> _isBusy; }
     <span>private</span> set
     {
         _isBusy = <span>value</span>;
          NotifyPropertyChanged(<span>&quot;IsBusy&quot;</span>);
      }
  }

   <span>public</span> IEnumerable&lt;MemberPM&gt; Members
  {
      get { <span>return</span> _members; }
      <span>private</span> set
     {
         _members = <span>value</span>;
         NotifyPropertyChanged(<span>&quot;Members&quot;</span>);
      }
  }

  <span>public</span> MemberPM SelectedMember
  {
      get { <span>return</span> _selectedMember; }
      set
      {
          _selectedMember = <span>value</span>;
          NotifyPropertyChanged(<span>&quot;SelectedMember&quot;</span>);
      }
  }
}


By using MEF’s ImportConstructor attribute, we can inject parts into the constructor, in Aspen we are injecting the IViewModelDataChannel. The ViewModel will work against the IViewModelDataChennel instead of directly with WCF RIA Services. By doing so we can write unit-test against the ViewModel without needing to mock the WCF RIA Services WebDomainClient class, and we can also easily replace the way the ViewModel need to communicate with the server.



ViewModel Locator

A ViewModel locator is used to locate the ViewModel for a View and use MEF to compose all parts needed for the ViewModel, like importing a IViewModelDataChannel. We are using the ViewModel locator that John Papa wrote, with some modification because I thought Silverlight 4 RTM will have a bugged fixed, but that wasn’t true, so we will change the code back to John’s workaround later. So my suggestion is that you take a look at John’s code instead of the one added to Aspen at the moment.

 

If you want to know when I publish a new blog post, you can follow me on twitter: http://www.twitter.com/fredrikn

Read More

MVVM, Data Channel, MEF, WCF RIA Services and ViewModel Locator – Silverlight 4.0

In the Aspen project I decided to use a ViewModel locator to find the ViewModel a View should use, I also use MEF for composition of parts. In this post I’m going to write about the MVVM implementation we use in the Aspen project, but first about the Data Channel used in Aspen.

Data Channel

The Aspen project uses WCF RIA Services to do the communication from the client to the server, we decided to use WCF RIA Services because it generates a good “base” for our ViewModel. When writing unit-test when using WCF RIA Services, we “have” to mock the WebDomainClient which is an class passed to the client-side DomainContext constructor. The WebDomainClient will handle the communication with the DomainService. When we write our tests we don’t want to mock the WebDomainClient and we don’t want to have my ViewModel to be dependent on a DomainContext, so instead we use IViewModelDataChannel. An abstraction on top of WCF RIA Services. By using the IViewModelDataChannel we can remove WCF RIA Services and use other frameworks for the communication, for example WCF, WCF Data Services, Web Service etc. Here is an example of a IViewModelDataChannel created for getting the Members stored into Aspen:

<span>public</span> <span>interface</span> IListMemberViewModelDataChannel
{
   <span>void</span> GetAllMembersAsync(Action&lt;IEnumerable&lt;MemberPM&gt;&gt; getAllMembersCompletedCallBack);
}

 

The following is the implementation of the IViewModelDataChannel using WCF RIA Services DomainContext:

[Export(<span>typeof</span>(IListMemberViewModelDataChannel))]
<span>public</span> <span>class</span> ListMemberViewModelDataChannel : IListMemberViewModelDataChannel
{
   MemberDomainContext _memberDomainContext = <span>new</span> MemberDomainContext();

   <span>public</span> <span>void</span> GetAllMembersAsync(Action&lt;IEnumerable&lt;MemberPM&gt;&gt; getAllMembersCompletedCallBack)
   {
      _memberDomainContext.Load&lt;MemberPM&gt;(
               _memberDomainContext.GetMembersQuery(),
               loadOperation =&gt;
              {
                   getAllMembersCompletedCallBack(loadOperation.Entities);
               }
              , <span>null</span>);
   }
}


Note: MEF is used to Export the IViewModelDataChannels and Import them into the ViewModel.

The following is a part of a ViewModel where the IListMemberViewModelDataChannel is used:

[ExportViewModel(<span>&quot;ListMemberViewModel&quot;</span>)]
<span>public</span> <span>class</span> ListMemberViewModel : BaseViewModel, IListMemberViewModel
{
        
 <strong><em><span>private</span> IListMemberViewModelDataChannel _listMemberViewService;</em></strong>

 <span>private</span> IEnumerable&lt;MemberPM&gt; _members = <span>null</span>;
 <span>private</span> MemberPM _selectedMember = <span>null</span>;

 <span>private</span> <span>bool</span> _isBusy = <span>false</span>;

<strong><em> [ImportingConstructor]
 <span>public</span> ListMemberViewModel(IListMemberViewModelDataChannel listMemberViewService)</em></strong>
 {
    Contract.Requires(listMemberViewService != <span>null</span>);
    Contract.Ensures(_listMemberViewService != <span>null</span>);

<strong><em>    <span>this</span>._listMemberViewService = listMemberViewService;</em></strong>

    <span>this</span>.IsBusy = <span>true</span>;
            
    <strong><em><span>this</span>._listMemberViewService.GetAllMembersAsync(GetAllMembersCompleted);</em></strong>
  }

<strong><em>  <span>private</span> <span>void</span> GetAllMembersCompleted(IEnumerable&lt;MemberPM&gt; result)
  {
     <span>this</span>.Members = result;
     <span>this</span>.IsBusy = <span>false</span>;
  }</em></strong>

  <span>public</span> <span>bool</span> IsBusy
  {
     get { <span>return</span> _isBusy; }
     <span>private</span> set
     {
         _isBusy = <span>value</span>;
          NotifyPropertyChanged(<span>&quot;IsBusy&quot;</span>);
      }
  }

   <span>public</span> IEnumerable&lt;MemberPM&gt; Members
  {
      get { <span>return</span> _members; }
      <span>private</span> set
     {
         _members = <span>value</span>;
         NotifyPropertyChanged(<span>&quot;Members&quot;</span>);
      }
  }

  <span>public</span> MemberPM SelectedMember
  {
      get { <span>return</span> _selectedMember; }
      set
      {
          _selectedMember = <span>value</span>;
          NotifyPropertyChanged(<span>&quot;SelectedMember&quot;</span>);
      }
  }
}


By using MEF’s ImportConstructor attribute, we can inject parts into the constructor, in Aspen we are injecting the IViewModelDataChannel. The ViewModel will work against the IViewModelDataChennel instead of directly with WCF RIA Services. By doing so we can write unit-test against the ViewModel without needing to mock the WCF RIA Services WebDomainClient class, and we can also easily replace the way the ViewModel need to communicate with the server.



ViewModel Locator

A ViewModel locator is used to locate the ViewModel for a View and use MEF to compose all parts needed for the ViewModel, like importing a IViewModelDataChannel. We are using the ViewModel locator that John Papa wrote, with some modification because I thought Silverlight 4 RTM will have a bugged fixed, but that wasn’t true, so we will change the code back to John’s workaround later. So my suggestion is that you take a look at John’s code instead of the one added to Aspen at the moment.

 

If you want to know when I publish a new blog post, you can follow me on twitter: http://www.twitter.com/fredrikn

Read More