vendredi 2 octobre 2015

C# Reflection.Emit, cast object to generated interface at runtime

I've an interface generated at runtime.

I'm creating its implementation at runtime using a DynamicProxy generator. For example:

Type generatedInterfaceType = UI.Helpers.ClassBuilderHelper.compileResultType(this.digitalInputs);

IInterceptor[] interceptors = new IInterceptor[1];
interceptors[0] = new Interceptors.Dynamic.ILinkedPropertiesInterceptor();

Type[] interfaces = new Type[1];
interfaces[0] = generatedInterfaceType;

object proxy =  DynamicExtensions.proxyGenerator.CreateClassProxyWithTarget(
    target.GetType(),
    interfaces,
    target,
    options,
    interceptors
);

Atfer the last sentence, proxy.GetType() backs me an Castle.Proxies.DigitalInputProxy. This type is created at runtime by Castle's DynamicProxyGenerator and it implements my interface also generated at runtime.

So after that:

Type proxyType = proxy.GetType(); //proxyType is Castle.Proxies.DigitalInputProxy
Type[] interfaces = proxyType.GetInterfaces();
Type myGeneratedInterface = interfaces[0]; // myGeneratedInterface is my generated interface.

The problem is that I don't know how to convert proxy to my interface generated at runtime. I've tried:

var dynamicTypeObject = Convert.ChangeType(proxy, myGeneratedInterface);

It throws me an InvalidCastException telling me: {"object must implement IConvertible"}.

Some help?





Aucun commentaire:

Enregistrer un commentaire