Mariano Ravinale's Blog

Sharing Experiences

Working with MvvmLight and Ninject cool extensions

with one comment

Today I would like to share some cool stuff that you can do with MvvmLight and Ninject extensions,

Other objective of this article is to show how to implement in a very quick way(easy steps) the AOP IANPC Interception (actions to be executed before or after the execution of every call to a method in our code) provided by Ninject Extensions(DI/Ioc) applied in the implementation of the interface INotifyPropertyChange as a simple atribute.

in other words :

We are going to change this code:

      public class SomeViewModel : ViewModelBase {

           private ObservableCollection<Item> _listCollection;
           public ObservableCollection<Item> ListCollection {
               get {
                   return _listCollection;
               }
               set {
                   _listCollection = value;
                   OnPropertyChanged("ListCollection");
               }
           }
       }

To this code:

       public class SomeViewModel : AutoNotifyViewModelBase {

           [NotifyOfChanges]
           public virtual ObservableCollection<Item> ListCollection { get; set; }

       }

A little of history and motivation first:

I’ve been doing some experiments with AOP, and then I saw a really nice article in code project about using Aspects applied to INotifyPropertyChanged (INPC), but I didn’t see a Ninject implementation so as always I’ve started to google about it.

What I saw was a gret article of Jonas Follesoe talking about using dynamic proxy for automatic INPC with Ninject I really recomend to read that post and download the project.

Reading article you can see that Ian Davis, the owner of interseption-extension for Ninject, contacted Jonas, and then he made his own adaptation of automatic INPC(IANPC) another great article

After couple week I had some free time and I wanted to see the source, of Ian davis project, and realised that the code of the IANPC was already inside, so I’ve started to make it work for share with you.

Let’s start to see the implementation:

First step is download the assemblies that we need:

Get Silverlight Ninject asemblies from GitHub.

Get Common Service locator from codeplex.

Ones that we finished to add all references to the project, let’s get to work!

In this example we are going to fill a List(Flick Behavior) with some mock items and add some effects.

Add a new Class named IocContainer.cs

image

Add the binding for each instance that you need in your project, as an example I’ve made some bindings for the main instance that I need to use:

public class IocContainer : NinjectModule {

       public override void Load() {

           this.Bind<ISampleDataSource>().To<SampleDataSource>();   

           //Services
           this.Bind<IDataService>().To<MockItemsService>();            

           //Pages
           this.Bind<MainPage>().ToSelf();

           //ViewModels
           this.Bind<MainViewModel>().ToSelf();

       }
   }

Add the Ioc Initialization into the app, Adding The Bootstrapper

    public class Bootstrapper
    {
        private static IKernel Container { get; set; }

        public static void Initialize()
        {
            Container = new StandardKernel(new DynamicProxy2Module(), new IocContainer());
            ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(Container));
        }

        public static void ShutDown()
        {
            Container.Dispose();
        }
    }

The normal implementation of this would be something like this:

var kernel = new StandardKernel(new IocContainer());

But we need to create proxies in order to do the Interception to our virtual members, that’s way we’ve added the new instance of DynamicProxy2Module, and way we need the reference to Castle.Core assembly.

Let’s do the last and important part of IANPC , the atribute NotifyOfChanges 🙂

[NotifyOfChanges]

public virtualObservableCollection<Item> ListCollection { get; set; }

But we need to implement the Interface IAutoNotifyPropertyChanged from Ninject.Extensions.Interseption in our view model otherwise it won’t work, but in MvvmLight we have a ViewModelBase with a diferent contract implementation instead to use OnPropertyChanged MvvmLight uses RaisePropertyChanged shit!!, I’ve been forced to create a new class, AutoNotifyViewModelBase that implements IAutoNotifyPropertyChanged and mvvm methods.

Implement the interface IAutoNotifyPropertyChanged in this case is already implmented in AutoNotifyViewModelBase .

public class MainViewModel : AutoNotifyViewModelBase {

      [NotifyOfChanges]
       public virtual ObservableCollection<Item> ListCollection { get; set; }

}

So far we have develop all things required to retrieve data from a service and fill our List Collection, we have the infrastructure using Ninject Ioc, and the interception IANPC Atributes cool right.

May the code be with you!

Mariano Ravinale.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License

Anuncios

Written by @mravinale

febrero 18, 2011 a 8:15 pm

Publicado en Silverlight

Una respuesta

Subscribe to comments with RSS.

  1. Hello,

    the link to the project download is broken (http://cid-86b4ae59157bdbba.office.live.com/self.aspx/Silverlight%20Projects/SLMvvmLightNinjectINPC.zip)
    Could you mail me the zip file ?
    Thx,
    Sven

    sven

    julio 28, 2011 at 1:19 pm


Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s

A %d blogueros les gusta esto: