Search code examples
c#mvvmcastle-windsorinterceptorproxy-classes

Generating interface implementation at runtime


I would like to ask is there a library which allows to generate implementation of interface at runtime with some additional features illustrated below.

Let's say I have interface like that:

interface ICustomer
{
    string Name {get;set;}
    string IAddress { get;set; }
}

interface IAddress
{
    string Street {get;set;}
}

I would like to do something like that:

ICustomer customer = someLibrary.Create<ICustomer>(bool createSubObjects)

where Create<T>() method would create an implementation like this at runtime:

class RuntimeCustomer : NotifyPropertyChanged,ICustomer 
//NotifyPropertyChanged would be hand written class
{
    string name;
    IAddress address = new RuntimeAddress(); 
    //if createSubObjects == false then `IAddress address = null`

    public string Name 
    {
       get { return name; }
       set { SetProperty(ref name, value); }
    }
    public IAddress Address
    { 
       get { return address; }
       set { SetProperty(ref address, value) }
    }
}

class RuntimeAddress : NotifyPropertyChanged, IAddress
{
    string street;
    public string Street 
    {
        get { return street; }
        set { SetProperty(ref,street, value) }
    }
}

Any idea please?


Solution

  • as jure said you can use DynamicProxy for this, but it would be aspects applied to a JIT'ed implementation of your interfaces. Check this out: http://jonas.follesoe.no/2009/12/23/automatic-inotifypropertychanged-using-dynamic-proxy/

    PostSharp excels at this use case as well, but it's done by compile-time weaving vs. runtime JIT'ing. http://www.postsharp.net/aspects/examples/inotifypropertychanged

    Hope this helps