Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make object dynamically implement an interface in code

I want to make this test pass - anyone got an idea how to do that?

public class Something
{
    public string Name {get; set}
}

public interface IWithId
{
    public Guid Id {get; set}
}

public class IdExtender 
{
    public static Object Extend(object toExtend)
    {
        ...?
    }
}

public class Tests 
{
    [Test]
    public void Should_extend_any_object()
    {
        var thing = new Something { Name = "Hello World!"};
        var extended = IdExtender.Extend(thing);
        Assert.IsTrue(extended is IWithId);
        Assert.IsTrue(extended.Id is Guid);
        Assert.IsTrue(extened.Name == "Hello World!");
    }
}

I guess something like this could be done with castle dynamic proxy, linfu,etc... but how?

like image 815
Jan Avatar asked Aug 16 '10 21:08

Jan


1 Answers

Using Castle DP (obviously)

Well - you will have to create a new object to return since you can't have an existing type gain a new interface as your program is executing.

To do this you will need to create a proxy and then replicate the state of your pre-existing object onto the proxy. DP does not do that OOTB. In v2.5 you could use the new class proxy with target but that would work only if all the properties on the type were virtual.

Anyway. You can make the new type gain the IWithId interface either by mixing in the proxy with an existing object that implement the property. Then the calls to members of the interface will be forwarded to the object.

Alternatively you can provide it as additional interface to implement and have an interceptor fill in the role of implementor.

like image 168
Krzysztof Kozmic Avatar answered Oct 20 '22 18:10

Krzysztof Kozmic