Problem implementing the future pattern using LinFu dynamic proxy

6 views
Skip to first unread message

mcintyre321

unread,
Jun 5, 2009, 10:42:08 AM6/5/09
to LinFu.Framework
I'm trying to write a Future pattern proxy which lazy loads a value
when it is called. It works (see the first test), but only if I
explicitly cast my create delegate. Is there some way to make the
second test pass without adding the cast?

internal class Future
{

public static T Create<T>(Func<T> get) where T : class
{
ProxyFactory factory = new ProxyFactory();
var interceptor = new GenericFuture<T>(get);
return factory.CreateProxy<T>(interceptor);
}

internal class GenericFuture<T> : IInterceptor
{
private readonly Func<T> getter;
private object instance;

public GenericFuture(Func<T> getter)
{
this.getter = getter;
}

public object Intercept(InvocationInfo info)
{
var target = instance ?? (instance = getter());
return info.TargetMethod.Invoke(target,
info.Arguments);
}
}
}

public class FutureTests
{
[Fact]
public void TestThatDoesntPass()
{
List<string> list = new List<string>() { "hello" };
IList<string> lazyList = Future.Create(() => list as
IList<string>); //<-- notice the cast
list[0] = "goodbye";
Assert.Equal("goodbye", lazyList[0]);
}

[Fact]
public void TestThatIWantToPass()
{
List<string> list = new List<string>() { "hello" };
IList<string> lazyList = Future.Create(() => list);
list[0] = "goodbye";
Assert.Equal("goodbye", lazyList[0]);
}
}

Philip_L

unread,
Jun 5, 2009, 5:26:52 PM6/5/09
to LinFu.Framework
Hi,

The reason why your test is failing is that you have your list
variable typed as a List<T> and when you make the call to
Future.Create, the compiler assumes that you're calling
Future.Create<List<T>>(), not Future.Create<IList<T>>(), and
LinFu.DynamicProxy can't proxy the List<T> type as well as it can
proxy the IList<T> interface. The reason why your test is works with
the cast is that it explicitly tells the compiler to call
Future.Create<IList<T>>(). I suspect that this has more to do with the
C# compiler than LinFu itself. Anyway, try it out, and let me know if
there's anything else that I can do for you. HTH :)

Regards,

Philip Laureano
Reply all
Reply to author
Forward
0 new messages