Dynamically generating types to implement INotifyPropertyChanged

As I mentioned in my last post, so much in Silverlight/WPF (especially when using MVVM) requires INotifyPropertyChanged for smooth operation that it would really be nice if there were first-class language support for augmenting classes in this way. INotifyPropertyChanged is pretty easily classified as a cross-cutting concern, I believe, and hence is a natural fit for aspect oriented programming techniques. For example, if its in your toolbelt, you could use Postsharp to do it pretty neatly, or other similar tools.

But, what I’m interested in, is if you want some simple code to implement this that stands alone and doesn’t have any external dependencies on 3rd party libraries, what would that look like? And how complicated is that? I was hoping to be able to use the new support for LambdaExpression.CompileToMethod in .NET 4 to make my life easier and avoid having to directly emit IL code, but it seems this API has some limitations (its only usable to generate static methods) at the moment that would prevent it being used in this manner. So, unfortunately, a degree in IL authoring is required to understand the code I’ll relate below.

The basic concept is that we will dynamically generate a type that inherits from the type for which we want to implement INotifyPropertyChanged. It will override the setters of any public or protected virtual properties, and raise the PropertyChanged event with the property name after the base setter has been called. This derived type implements the INotifyPropertyChanged event and is the actual type that you will create an instance for.

Things to note with this approach:

  1. This does not attempt to “wrap” a live instance of the class you trying to augment with the interface. It instead creates a derived type that you should instantiate rather than the actual type. This approach could be modified to wrap a live instance without too much additional effort.
  2. The implementation is not yet thread-safe.
  3. This approach relies on the public properties being marked as virtual so that they are overridable in the dynamically generated type.
  4. As I’m not actually using this code (its mostly an experiment, currently), it is a bit rough, so use at your own risk, and you may need to do some polishing, but this could act as a jumping off point if you are interested in this kind of approach, or or trying to learn more about runtime IL generation.
  5. This was written against the Silverlight subset of the Framework, so should work fine against Silverlight or WPF.

Let’s start with how you can use the code. If we have a class, Test:

public class Test
{
    public virtual double TestDouble { get; set; }
    public virtual string TestString { get; set; }
}

We can create an instance of it and use it in this way:

Test testObj = ProxyProvider.Instance.NewProxy<Test>();
(testObj as INotifyPropertyChanged).PropertyChanged +=
    (o, e) => System.Diagnostics.Debug.WriteLine(
    "property changed: " + e.PropertyName);
testObj.TestDouble = 5;
testObj.TestString = "testtest";

And when we run the application, the debug statements confirm that the property changed events are firing. So, how is this accomplished?

Let’s start with the rather boring singleton that furnishes the augmented types:

public class ProxyProvider
    {
        private static volatile ProxyProvider _instance = null;
        public static ProxyProvider Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ProxyProvider();
                }
                return _instance;
            }
        }

        private ProxyProvider()
        {
        }

        private Dictionary<Type, Type> _proxyTypes = new Dictionary<Type, Type>();

        public T NewProxy<T>()
        {
            return (T)ProxyHelper(typeof(T));
        }

        private object ProxyHelper(Type type)
        {
            Type proxyType;
            if (_proxyTypes.TryGetValue(type, out proxyType))
            {
                return Activator.CreateInstance(proxyType);
            }
            else
            {
                proxyType =
                INotifyPropertyChangedProxyTypeGenerator
                .GenerateProxy(type);
                _proxyTypes.Add(type, proxyType);
                return Activator.CreateInstance(proxyType);
            }
        }

        public object NewProxy(Type type)
        {
            return ProxyHelper(type);
        }
    }

This basically just maintains a dictionary of generated types so they don’t need to be generated anew each time. The real work of the dynamic type generation is occurring in the INotifyPropertyChangedProxyTypeGenerator:

public class INotifyPropertyChangedProxyTypeGenerator
    {
        private static AssemblyBuilder _ab;
        private static ModuleBuilder _mb;

INotifyPropertyChangedProxyTypeGenerator needs some Reflection.Emit objects that aid in the construction of dynamic types. The AssemblyBuilder manages the dynamic assembly we are creating in memory, and the ModuleBuilder manages the module that will contain our types.

        public static Type GenerateProxy(Type type)
        {
            if (_ab == null)
            {
                var assmName = new AssemblyName("DynamicAssembly");
                _ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
                             assmName,
                             AssemblyBuilderAccess.Run);
                _mb = _ab.DefineDynamicModule(assmName.Name);
            }

            // public class [TypeName]__proxy
            //    : [TypeName], INotifyPropertyChanged
            TypeBuilder typeBuilder = _mb.DefineType(
                type.Name + "__proxy", TypeAttributes.Public, type);
            typeBuilder.AddInterfaceImplementation(
            typeof(INotifyPropertyChanged));

            FieldBuilder eventField =
            CreatePropertyChangedEvent(typeBuilder);

            MethodBuilder raisePropertyChanged =
            CreateRaisePropertyChanged(typeBuilder, eventField);

            // get all the public or protected
            // virtual property setters.
            var props = from p in
                            type.GetProperties(
                                BindingFlags.Public |
                                BindingFlags.NonPublic |
                                BindingFlags.Instance |
                                BindingFlags.FlattenHierarchy)
                        where p.GetSetMethod().IsVirtual &&
                        (p.GetSetMethod().IsPublic ||
                        p.GetSetMethod().IsFamily)
                        select p;
            props.ToList().ForEach(
            (item) => WrapMethod(
            item, raisePropertyChanged, typeBuilder));

            Type ret = typeBuilder.CreateType();
            return ret;
        }

This is the top level script of actions that are required to generate the dynamic type:

  1. Assert that our AssemblyBuilder and ModuleBuilder are created.
  2. Create the dynamic type based off the original type’s name.
  3. Cause the new type to implement the interface INotifyPropertyChanged.
  4. Create the PropertyChanged event on the new type to implement the interface.
  5. Create a method on the new type called RaisePropertyChanged, which will be called from the property setters.
  6. For each public or protected virtual property, override the setter method, having each new setter call RaisePropertyChanged.
  7. Return the created type.

Now, let’s drill down further into how these steps are accomplished. First, let’s see how we create the PropertyChanged event:

        private static FieldBuilder CreatePropertyChangedEvent(
        TypeBuilder typeBuilder)
        {
            // public event PropertyChangedEventHandler PropertyChanged;

            FieldBuilder eventField =
                typeBuilder.DefineField("PropertyChanged",
                typeof(PropertyChangedEventHandler),
                FieldAttributes.Private);
            EventBuilder eventBuilder =
                typeBuilder.DefineEvent(
                "PropertyChanged",
                EventAttributes.None,
                typeof(PropertyChangedEventHandler));

            eventBuilder.SetAddOnMethod(
            CreateAddRemoveMethod(typeBuilder, eventField, true));
            eventBuilder.SetRemoveOnMethod(
            CreateAddRemoveMethod(typeBuilder, eventField, false));

            return eventField;
        }

The event consists of the actual event definition which has an Add method and a Remove method that indicate what occurs when users += or –= the event, and the delegate that will store the delegate chain associated with the event. This method will create the event and backing delegate definitions on the type, and then create the add and remove methods for the event by calling this method:

 private static MethodBuilder CreateAddRemoveMethod(
            TypeBuilder typeBuilder, FieldBuilder eventField, bool isAdd)
        {
            string prefix = "remove_";
            string delegateAction = "Remove";
            if (isAdd)
            {
                prefix = "add_";
                delegateAction = "Combine";
            }
            MethodBuilder addremoveMethod =
            typeBuilder.DefineMethod(prefix + "PropertyChanged",
               MethodAttributes.Public |
               MethodAttributes.SpecialName |
               MethodAttributes.NewSlot |
               MethodAttributes.HideBySig |
               MethodAttributes.Virtual |
               MethodAttributes.Final,
               null,
               new[] { typeof(PropertyChangedEventHandler) });
            MethodImplAttributes eventMethodFlags =
                MethodImplAttributes.Managed |
                MethodImplAttributes.Synchronized;
            addremoveMethod.SetImplementationFlags(eventMethodFlags);

            ILGenerator ilGen = addremoveMethod.GetILGenerator();

            // PropertyChanged += value; // PropertyChanged -= value;
            ilGen.Emit(OpCodes.Ldarg_0);
            ilGen.Emit(OpCodes.Ldarg_0);
            ilGen.Emit(OpCodes.Ldfld, eventField);
            ilGen.Emit(OpCodes.Ldarg_1);
            ilGen.EmitCall(OpCodes.Call,
                typeof(Delegate).GetMethod(
                delegateAction,
                new[] { typeof(Delegate), typeof(Delegate) }),
                null);
            ilGen.Emit(OpCodes.Castclass, typeof(
            PropertyChangedEventHandler));
            ilGen.Emit(OpCodes.Stfld, eventField);
            ilGen.Emit(OpCodes.Ret);

            MethodInfo intAddRemoveMethod =
            typeof(INotifyPropertyChanged).GetMethod(
            prefix + "PropertyChanged");
            typeBuilder.DefineMethodOverride(
            addremoveMethod, intAddRemoveMethod);

            return addremoveMethod;
        }

The add or remove method are constructed using the following steps:

  1. Create the method named add_PropertyChanged or remove_PropertyChanged. A good trick for determining method attributes or implementation flags (or method body for that matter) if you are unsure is to write what you are trying to emulate in c# and compile it, and then use Reflector to examine the IL code that was generated.
  2. Emit code that adds or removes the provided delegate to the backing delegate chain for the event.
  3. Specify that the method is overriding the expected method on the INotifyPropertyChanged interface.
  4. Return the resulting method.

The RaisePropertyChanged method we create will simply call the delegate chain backing the PropertyChanged event if it is non-null:

private static MethodBuilder CreateRaisePropertyChanged(
TypeBuilder typeBuilder, FieldBuilder eventField)
        {
            MethodBuilder raisePropertyChangedBuilder =
                typeBuilder.DefineMethod(
                "RaisePropertyChanged",
                MethodAttributes.Family | MethodAttributes.Virtual,
                null, new Type[] { typeof(string) });

            ILGenerator raisePropertyChangedIl =
            raisePropertyChangedBuilder.GetILGenerator();
            Label labelExit = raisePropertyChangedIl.DefineLabel();

            // if (PropertyChanged == null)
            // {
            //      return;
            // }
            raisePropertyChangedIl.Emit(OpCodes.Ldarg_0);
            raisePropertyChangedIl.Emit(OpCodes.Ldfld, eventField);
            raisePropertyChangedIl.Emit(OpCodes.Ldnull);
            raisePropertyChangedIl.Emit(OpCodes.Ceq);
            raisePropertyChangedIl.Emit(OpCodes.Brtrue, labelExit);

            // this.PropertyChanged(this,
            // new PropertyChangedEventArgs(propertyName));
            raisePropertyChangedIl.Emit(OpCodes.Ldarg_0);
            raisePropertyChangedIl.Emit(OpCodes.Ldfld, eventField);
            raisePropertyChangedIl.Emit(OpCodes.Ldarg_0);
            raisePropertyChangedIl.Emit(OpCodes.Ldarg_1);
            raisePropertyChangedIl.Emit(OpCodes.Newobj,
                typeof(PropertyChangedEventArgs)
                .GetConstructor(new[] { typeof(string) }));
            raisePropertyChangedIl.EmitCall(OpCodes.Callvirt,
                typeof(PropertyChangedEventHandler)
                .GetMethod("Invoke"), null);

            // return;
            raisePropertyChangedIl.MarkLabel(labelExit);
            raisePropertyChangedIl.Emit(OpCodes.Ret);

            return raisePropertyChangedBuilder;
        }

If you are new to IL generation and mostly use C#, the way that the if statement unrolls into, basically, a goto may be new to you. Although much more advanced, IL code is in many ways very similar to Assembly language due to the need to translate IL code into native code very efficiently. The IL code emitted here will check to see if the delegate chain associated with PropertyChanged is null in which case it will branch to the exit label and skip the invocation of the delegate chain.

Last but not least, here is how we will override each setter, call its base implementation and then call RaisePropertyChanged:

        private static void WrapMethod(PropertyInfo item,
        MethodBuilder raisePropertyChanged, TypeBuilder typeBuilder)
        {
            MethodInfo setMethod = item.GetSetMethod();

            //get an array of the parameter types.
            var types = from t in setMethod.GetParameters()
                        select t.ParameterType;

            MethodBuilder setMethodBuilder = typeBuilder.DefineMethod(
                setMethod.Name, setMethod.Attributes,
                setMethod.ReturnType, types.ToArray());
            typeBuilder.DefineMethodOverride(
            setMethodBuilder, setMethod);
            ILGenerator setMethodWrapperIl =
                setMethodBuilder.GetILGenerator();

            // base.[PropertyName] = value;
            setMethodWrapperIl.Emit(OpCodes.Ldarg_0);
            setMethodWrapperIl.Emit(OpCodes.Ldarg_1);
            setMethodWrapperIl.EmitCall(
            OpCodes.Call, setMethod, null);

            // RaisePropertyChanged("[PropertyName]");
            setMethodWrapperIl.Emit(OpCodes.Ldarg_0);
            setMethodWrapperIl.Emit(OpCodes.Ldstr, item.Name);
            setMethodWrapperIl.EmitCall(
            OpCodes.Call, raisePropertyChanged, null);

            // return;
            setMethodWrapperIl.Emit(OpCodes.Ret);
        }

The steps involved are:

  1. Create the method using the same settings of the Set method we are overriding.
  2. Emit IL that calls the base setter method.
  3. Emit IL that calls the RaisePropertyChanged method passing in the name of the current property.

And that’s basically it! We’ve created a dynamic assembly, a dynamic module and a dynamic type that inherits from the target type, but also implements INotifyPropertyChanged, and overrides any overridable setters and has them raise the PropertyChanged event! Pretty neat huh?

So what’s next? I’m somewhat satisfied with this because it employed a self contained and small amount of code to massively reduce the amount of boilerplate needed if you have a lot of types that need to implement this interface. But, really, it can be a bit too onerous or ill-advisable to absolutely require that properties be overridable to take advantage of this (not to mention error-prone!). So I think I’ll investigate what methods I might use to rewrite IL in an assembly as a post-compile step to improve on all this. The obvious and easiest choice is to use PostSharp to do this kind of IL rewriting, but as I and others are not always in a position to leverage 3rd party tools, I’m interested in how complex a stand-alone solution would be.

Well, until next time ;-)

About these ads

3 Responses to Dynamically generating types to implement INotifyPropertyChanged

  1. [...] internals? Well, I was curious as to how hard it would be to adapt the code I wrote recently for generating dynamic types to implement INotifyPropertyChanged to generate types that had the same properties as an anonymous type except read-write and [...]

  2. DanS says:

    Using your code as a guide, I’m trying do something similar in a C3 win forms app. I’m using my dynamically generated types to store data in a BindingList. Everything is working except for the INotifyPropertyChanged part.
    My problem is eventField is null when I get here:
    il.Emit(OpCodes.Ldfld, eventField);
    il.Emit(OpCodes.Ldnull);
    il.Emit(OpCodes.Ceq);
    il.Emit(OpCodes.Brtrue, labelExit);

    I’ve been through my code over and over and can’t find where I’m going wrong. It feels like something is missing that should be “initializing” eventField.
    When I compare my dynamic version with a static version with ILDASM the only difference I see is with the add_PropertChanged and remove_PropertyChange methods.
    Also I’m not able to use MethodImplAttributes.Synchronized;

    Any help would be greatly appreciated.

  3. cv says:

    great! works like a charm, that just saved my day

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: