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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With