Sunday, March 7, 2010

MVVM with MEF in Silverlight: Video Tutorial

This is a video tutorial to introduce beginners to how to use both MVVM (Model-View-ViewModel) and MEF (Managed Extensibility Framework) with Silverlight (should work for versions 3 and 4). Of course, some "veterans" may want to watch as well in case you've missed some of the fundamentals, or have a clever way to do something that you can share in the comments for future visitors to the page. Want to learn more about MEF? Watch my video series, Fundamentals of the Managed Extensibility Framework.

In this edition, I build a simple application that allows the user to check a preference on the screen (whether they prefer squares over circles) and then displays a square or a circle. We use MVVM and wire everything together with MEF.

Download the source code: MEFMVVMDemoSln.zip

Click here to watch the video directly if it doesn't appear in the frame below (recommended to watch in full screen): Watch the video in a separate window

Here is the final application:

Download the source code: MEFMVVMDemoSln.zip

Jeremy Likness

30 comments:

  1. Nice video, i have the same opinion,MEF works great with mvvm pattern. in my case i found it was very good in a project i had where i use the mvvm light. It's easy to keep it simple and build a little more complex apps in a quicker way.

    Thanks, and good work.

    ReplyDelete
  2. Great demo.
    But after seeing you remove and sort using directives in the demo so many times. I thought of actually writing a blog post on how I have done to make it more easier. http://blog.prabir.me/post/Visual-Studio-Tips-and-Tricks-IX.aspx

    ReplyDelete
  3. The video is not working? I tried the separate window as well...

    ReplyDelete
  4. Hmmm, just tested it here in multiple browsers and it worked fine. Silly question ... do you have Silverlight? Assuming so if you are trying to watch a video about it.

    ReplyDelete
  5. What is the need to import the mainviewmodel on every UserControl (part)? One import on mainpage en datacontext inheritance takes care off it.

    ReplyDelete
  6. Good point! That is a nuance of design and how decoupled you want your application to be. If you are truly treating controls as separate composable parts, then you can't assume they'll be in a hierarchy that has that model available. Often each part may have its own view model or sub view model. On the flipside, if you architect the application so that there is an assumption of the hierarchy, then of course you can get to the model via DataContext and not have to import it. This was a way to demonstrate reusability across the application no matter how deep or where the composable part comes in.

    ReplyDelete
  7. I was just going to post a comment that the video is not working for me as well. Then, I decided to go away from Chrome browser and try the page in IE. And it is fine here. So, I guess it is the incompatibility issue between Silverlight and Chrome that cause the video to not work.
    Przemek

    ReplyDelete
  8. Thanks for the clarification. I was debating posting the direct MP4 link but rationalized, "Hey, this is about Silverlight, so why not host it in a Silverlight control?"

    ReplyDelete
  9. Useful demo, simple and yet demonstrates various concepts and programming techniques.
    Thanks

    ReplyDelete
  10. I recently installed the Latest SL4 full release and the VS 2010 Premium Trial but cannot find the System.ComponentModel.Composition.Initialization.dll anywhere other than your source. And when I use the one from your source I am getting reflection warnings? Is this now obsolete with the latest release? Thanks

    ReplyDelete
  11. If you're targeting Silverlight 3 then you need Preview 9 from CodePlex. If you're targeting Silverlight 4, it should have installed with the Silverlight 4 tools and be available on the .NET tab for references.

    ReplyDelete
  12. Thanks Jeremy. Strange as I did download the SL4 tools as soon as it was available last Thursday on two machines and both are missing some dlls. I reinstalled the SL4 tools on one and now all the appropriate dlls appear. If anyone else is having a similar issue try to reload the SL4 tools.

    Thanks again

    ReplyDelete
  13. I'm on this page
    http://www.wintellect.com/CS/files/folders/sample_files/entry12353.aspx

    Now, how do I get the MEFMVVMDemoSln.zip?

    Please, englighten me.

    ReplyDelete
  14. Click the "Download" button in the upper right.

    ReplyDelete
  15. How do I do this is WPF?

    WPF has no CompositionInitializer.SatisfyImports.

    Thanks.

    ReplyDelete
  16. Jeremy great stuff.

    Can I ask you what tools you used to record, edit, and display the video? It is nice and clear.

    Thanks.

    ReplyDelete
  17. Sure, ask away! The setup I use is actually straightforward. I use Expression Encoder (part of the Expression Suite that Blend comes with) to make the recordings and captures. For audio, I invested in a Logitech ClearChat USB headset. That's it!

    ReplyDelete
  18. nice - i just got the aha moment :-)

    i'd recommend upgrading your demos to VS2010 though...

    john

    ReplyDelete
  19. nice, enjoyed it.

    ps. I loaded solution in VS 2010/ Had a CAS Policy issue with loading MEF dependencies. Easily rectified by adding entry in devenv.exe.config,





    More info here,

    http://msdn.microsoft.com/en-us/library/dd409252.aspx

    Thanks Jeremy

    ReplyDelete
  20. Hey Jeremy,

    Great tutorial. I've done a silverlight chess site as noted in my profile. I want to abstract it out more using control factories and MEF. I have this ControlFactory which can create menus, toolbars, what have ya. I want MEF to new up a ControlFactory but setting the actual content of a control will have to be like "Factory.Menu()", what have ya. Does this seems right to you as in:

    private ControlFactory _controlFactory;

    [Import]
    public ControlFactory Factory
    {
    get{ return _controlFactory; }
    set{ _controlFactory = value; }
    }

    [Import]
    public MenuControl Menu
    {
    get{ return MenuRegion.Content as MenuControl; }
    set{ MenuRegion.Content = Factory.Menu(); }
    }

    I haven't even tried this out yet but if I want MEF to use the factory, this seems like the only way to do it. Any thoughts on this approach?

    Thanks for your great tuttorials.

    David

    ReplyDelete
  21. That certaily seems a valid way to do it, it really depends on the other details of the application as a whole. We have a new series slowly being updated/posted to http://www.mefcontrib.com/

    ReplyDelete
  22. Hey Jeremy, I actually stayed up a bit late last night playing around with the idea I threw at ya, and it seems to work(with a slight hack) but it seems like I can make it better though. I know MEF has these constructor imports, something to that effect which I've done before but in this case the constructor for the MenuControl is passed a generic func as in :

    MenuControl(CreateControl(() => new Menu(some args go here...))) and this "CreateControl" method is somthing like this:

    TComponent CreateControl(...) I'm not even close to knowing how to get MEF to pass this FUNC into the constructor. I will read the link you sent out. Youre one heck of a resource.

    Thanks again.

    ReplyDelete
  23. Jeremy,

    I figured out a work around for MEF not directly supporting generic export/imports. I sent another comment regarding this but something wierd happened so I'll send the jist of it here.

    I read your other post regarding the generic export/import issue, and as I found it very helpful, my issue turned out to be a tad different. If the classes I'm using in the solution I'm about to explain below did not have constructors with parameters, your solution would have worked. The abstract factory I'm working with is a topic in itself.

    The way I got around it was to have MEF new up a generic Func with a view component and a builder component and then simply pass this func to a control factory method. This method is completely generic and returns a builder object of type T. There's some other magic going on inside this factory method but wanted to keep this short and sweet. Since this factory method is generic, if I want to have a different type of builder returned, I simply change the definition of the func that i pass into the factory method, that's it.

    Anyone reading this, if one would like a code sample, hit me up at dwhitten15@hotmail.com.

    The whole MEF thing has inspired me to revamp my chess website at http://www.whittenizer.com/ to use MEF and to abstarct it out more.

    Thanks again,

    David

    ReplyDelete
  24. Jeremy,
    Thanks for the great video! Great example of using MVVM with MEF. BTW, if you were writing tests for this, what kinds of things would you look for with the MEF composition of parts, etc? Anything in particular?
    Thanks Again!
    Bill

    ReplyDelete
  25. Could not watch the post. I tried in separate window but not working.

    ReplyDelete
  26. Couldn't watch the video. Tried both IE and chrome , here and in separate window.(have latest version of SL installed too)

    ReplyDelete
  27. Thank you for this video. Good idea to include MEF as an additional learning. You are very sympathic.
    I'm coming from the MVP side. Your sample is not really an implementation of the Model-View-ViewModel pattern because there is no Model in your solution. Right? The Model is integrated in the ViewModel. Sure - because you have only one Property "Prefere Square" - you did this to be faster.
    If you have one Model on multiple ViewModels (and using MEF) and each ViewModel has its View than it is important to devide the Model and the ViewModel.
    I see often that there are samples based on MVVM without any Model. Do you think its correct to put any Properties like "PrefereSquare" into the ViewModel?

    Thank you. I will look for more samples in your Blog to learn.
    Stefan Werdenberg, Switzerland

    ReplyDelete
  28. Does using MEF obviate the need for Unity when impementing MVVM? I am new to all of this design pattern and tools and not sure which products do what and what is the recommended way for SIMPLE MVVM.

    Thanks,
    Cindy K.

    ReplyDelete
  29. Wow, no tutorial has made me feel more like giving up than this one. Of course, I'm a rank amateur with Prism, MEF, MVVM, etc. However, I have a basic understanding of the core concepts and motivations. But you flit from page to page without reminding us that you now in the view, now in the viewmodel, not back in the view, etc., and most importantly, WHY you are back in there. At least that's my impression. Further you use that tool so fast and furiously that it's clear you think we all have that tool too, know how to use it, and can use it in our sleep, as you can clearly do. I cannot. Even if I could, I'd prefer your tutorial to go through all the steps manually, showing me step by step what is taking place and how *I* can recreate each step, knowing what I did, why I did it, and how to do it. The tool just really obfuscates things -- for me. I'm sure there are others who might also like to see the real process, at the introductory level. I have a hard time considering this tutorial as one for "beginners," as your introduction claims. Could you maybe sometime make some *true* beginner tutorials, maybe like ones that assume we don't know Jack about MEF and MVVM? I do appreciate your conversational style, so I look forward to other tutorials of yours. Hopefully some of them are at my level.

    ReplyDelete
    Replies
    1. LOL, my sentiments, too!

      I agree with Anonymous (Aug 12, 2012), at least partially. I just finished taking your tutorial, but I am now preparing to spend many hours with the code trying to *really* understand what is going on and what you are trying to impart to us. I also agree with some the other comments, too, in that your tutorial is at the right level, your conversational style was pleasant to listen to, etc.

      HOWEVER, I also would have liked you to explain when and why you moved from one level to the other, from one file to the other, where the "model" comes into play, etc. The tool usage didn't bother me much, but occasionally I had to rewind and then play/pause/play/pause/play pause to catch the tips on what the tool was doing. Rather, I had problems with the too-informal commentary about which layer you were working in at any moment and why (e.g., V, M, or VM). I am getting ready to try drawing a layer diagram showing importa/exports, in hopes that that will clear some things up for me.

      So to once again agree with Anonymous, I sure would love to see you do some new MVVM and MEF tutorials, reads, diagrams, etc. that are *truly* for the beginner in these areas. I've been programming many, many years, but I find MVVM and MEF a bit difficult to comprehend. So the tutorials don't have to be for beginners to programming, just beginners to MEF and MVVC -- detail by detail.

      Thanks in advance! :-)

      Delete