Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a DynamicObject that supports an Interface?

Can I define a class which derives from DynamicObject and supports an interface (ICanDoManyThings) without having to implement each method in the interface?

I'm trying to make a dynamic proxy object, and want the method invocations on this class to be handled by the implementation of MyProxyClass.TryInvokeMember, which may or may not pass them on to a wrapped object.

Is this possible?

Thanks

like image 835
gap Avatar asked Jul 15 '11 19:07

gap


People also ask

How do you create a dynamic object?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.

What is DynamicObject?

A brief explanation of Dynamic objects is, Dynamic objects expose members such as properties and methods at run time, instead of compile time. This enables you to create objects to work with structures that do not match a static type or format.

What is a dynamic class C#?

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.


2 Answers

ImpromptuInterface does exactly this and it works with ANY IDynamicMetaObjectProvider including DynamicObject subclasses and ExpandoObject.

using ImpromptuInterface;
using ImpromptuInterface.Dynamic;

public interface IMyInterface{

   string Prop1 { get;  }

    long Prop2 { get; }

    Guid Prop3 { get; }

    bool Meth1(int x);
}

...

//Dynamic Expando object
dynamic tNew = Build<ExpandoObject>.NewObject(
         Prop1: "Test",
         Prop2: 42L,
         Prop3: Guid.NewGuid(),
         Meth1: Return<bool>.Arguments<int>(it => it > 5)
);

IMyInterface tActsLike = Impromptu.ActLike<IMyInterface>(tNew);

Linfu won't actually use DLR based objects and rather uses it's own naive late binding which gives it a SERIOUS performance cost. Clay does use the dlr but you have to stick with Clay objects which are designed for you to inject all behavior into a ClayObject which isn't always straightforward.

like image 141
jbtule Avatar answered Oct 24 '22 04:10

jbtule


With Clay, you can.

An example:

public interface IMyInterface
{
    string Prop1 { get; }

    long Prop2 { get; }

    Guid Prop3 { get; }

    Func<int, bool> Meth { get; }
}

//usage:

dynamic factory = new ClayFactory();
var iDynamic = factory.MyInterface
(
    Prop1: "Test",
    Prop2: 42L,
    Prop3: Guid.NewGuid(),
    Meth: new Func<int, bool>(i => i > 5)
);

IMyInterface iStatic = iDynamic;

This article shows few more ways to achieve this.

like image 3
Daniel A. White Avatar answered Oct 24 '22 05:10

Daniel A. White