Mobile Zone is brought to you in partnership with:

My name is Pieter De Rycke, I am a Belgian technical .Net architect working in the insurance sector. I am always eager to learn new technologies and I like to keep up with the latest innovations and trends in the IT sector. I am a big believer in web services for interoperability between platforms. Pieter is a DZone MVB and is not an employee of DZone and has posted 36 posts at DZone. You can read more from them at their website. View Full User Profile

Dynamically adding RaisePropertyChanged to MVVM Light ViewModels using Reflection.Emit

01.02.2012
| 3893 views |
  • submit to reddit
I like the clean separation between views and view models made possible by the MVVM pattern. But I don’t like the code pattern required to implement RaisePropertyChanged in simple properties.
private static string someProperty;

public string SomeProperty
{
    get
    {
        return someProperty;
    }
    set
    {
        someProperty = value;
        RaisePropertyChanged("SomeProperty");
    }
}

I would prefer an implementation like this:

[RaisePropertyChanged]
public string SomeProperty { get; set; }

Implementing this is possible with a principle called AOP (Aspect Oriented Programming). Although C# is an OOP (Object Oriented Programming) language, various people and companies have made AOP in C# easily possible. As I am a passionate technologist, I off course wanted to understand how this “magic” works Glimlach.

Two options are possible: post compilation by modifying the compiled assemblies or dynamic creation of proxy classes at runtime. In this article, I will present how you can implement this yourself. But because various high quality tools and frameworks are available, I recommend not to implement this yourself for production code.

Post compilation can be done by an AOP tool like PostSharp. Dynamic proxy creation is done by libraries such as Castle DynamicProxy or by IOC containers like Microsoft Unity.

Dynamic proxy Creation

I have chose to use dynamic proxy creation in my example. I will not make my code generic, but instead I will hardcode the required functionality. I assume that you will be capable of generalizing this yourself, if required. The code relies on MVVM Light, but you could replace this library with any other MVVM library.

The API that allows this dynamic behavior is Reflection.Emit and it allows you to create classes at runtime using MSIL code. MSIL is the assembly of the .Net CLR. Most .Net programmers have probably never seen this language. By using a smart trick, only a limited knowledge is required.

Microsoft has an MSIL disassembler called “ILDASM”. You can use this tool easily if you launch it from the “Visual Studio 2010 command prompt”. To know the required MSIL code for our prototype, we first create what we want in c#, compile it and then look at the generated MSIL code with ILDASM.

The proxy we want to create dynamically (SampleViewModelExtended) looks like:

// Dynamic proxy created manually
public class SampleViewModelExtended : SampleViewModel
{
    public override string SomeProperty
    {
        get
        {
            return base.SomeProperty;
        }
        set
        {
            base.SomeProperty = value;
            RaisePropertyChanged("SomeProperty");
        }
    }
}

public class SampleViewModel : ViewModelBase
{
    [RaisePropertyChanged]
    public virtual string SomeProperty { get; set; }
}

Please note: we have to make the properties virtual in the base class, because otherwise we cannot overwrite the setters in the derived class.

If we compile this and look at the MSIL, we get:

ILDASM_required_MSIL_code

Having the required MSIL code, the only thing we now have to do is generating the MSIL dynamically using Reflection.Emit.

public static class ReflectionEmitViewModelFactory
{
    public static T CreateInstance<T>()
        where T : ViewModelBase
    {
        Type vmType = typeof(T);

        VerifyViewModelType(vmType);

        // Create everything required to get a module builder
        AssemblyName assemblyName = new AssemblyName("SmartViewModelDynamicAssembly");
        AppDomain domain = AppDomain.CurrentDomain;
        AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            //AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

        string dynamicTypeName = Assembly.CreateQualifiedName(vmType.AssemblyQualifiedName, "Smart" + vmType.Name);

        TypeBuilder typeBuilder = moduleBuilder.DefineType(dynamicTypeName,
            TypeAttributes.Public | TypeAttributes.Class, vmType);

        MethodInfo raisePropertyChangedMethod = typeof(ViewModelBase).GetMethod("RaisePropertyChanged",
            BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string) }, null);

        foreach (PropertyInfo propertyInfo in FindNotifyPropertyChangCandidates<T>())
            UpdateProperty(propertyInfo, typeBuilder, raisePropertyChangedMethod);

        Type dynamicType = typeBuilder.CreateType();

        return (T)Activator.CreateInstance(dynamicType);
    }

    private static void VerifyViewModelType(Type vmType)
    {
        if (vmType.IsSealed)
            throw new InvalidOperationException("The specified view model type is not allowed to be sealed.");
    }

    private static IEnumerable<PropertyInfo> FindNotifyPropertyChangCandidates<T>()
    {
        return from p in typeof(T).GetProperties()
                where p.GetSetMethod() != null && p.GetSetMethod().IsVirtual &&
                p.GetCustomAttributes(typeof(RaisePropertyChangedAttribute), false).Length > 0
                select p;
    }

    private static void UpdateProperty(PropertyInfo propertyInfo, TypeBuilder typeBuilder,
        MethodInfo raisePropertyChangedMethod)
    {
        // Update the setter of the class
        PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyInfo.Name,
            PropertyAttributes.None, propertyInfo.PropertyType, null);

        // Create set method
        MethodBuilder builder = typeBuilder.DefineMethod("set_" + propertyInfo.Name,
            MethodAttributes.Public | MethodAttributes.Virtual, null, new Type[] { propertyInfo.PropertyType });
        builder.DefineParameter(1, ParameterAttributes.None, "value");
        ILGenerator generator = builder.GetILGenerator();

        // Add IL code for set method
        generator.Emit(OpCodes.Nop);
        generator.Emit(OpCodes.Ldarg_0);
        generator.Emit(OpCodes.Ldarg_1);
        generator.Emit(OpCodes.Call, propertyInfo.GetSetMethod());

        // Call property changed for object
        generator.Emit(OpCodes.Nop);
        generator.Emit(OpCodes.Ldarg_0);
        generator.Emit(OpCodes.Ldstr, propertyInfo.Name);
        generator.Emit(OpCodes.Callvirt, raisePropertyChangedMethod);
        generator.Emit(OpCodes.Nop);
        generator.Emit(OpCodes.Ret);
        propertyBuilder.SetSetMethod(builder);
    }
}

Once you know the MSIL to generate, using Reflection.Emit is very straightforward. By using the sample code provided above, we can know create dynamic ViewsModels very easy:

SampleViewModel viewModel = ReflectionEmitViewModelFactory.CreateInstance<SampleViewModel>();
Source:  http://pieterderycke.wordpress.com/2011/07/08/dynamically-adding-raisepropertychanged-to-mvvm-light-viewmodels-using-reflection-emit/


Published at DZone with permission of Pieter De Rycke, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)