Question

This question already has an answer here:

I am wondering whether I can upgrade a basic IoC container I am using to support lazy load. So if I have registered IFoo, I would like the IoC container to know how to fulfil both of the following dependencies (the first being the standard way IoC containers work, while the second returns a simple delegate that calls into the container for an IFoo when it is invoked).

public Bar(IFoo x)

public Bar2(Func<IFoo> lazyFoo)

The problem comes when I try to write the code that will actually do this. Is there a syntax that will make the following pseudo-code compile?

public T Resolve<T>()
{
    if (T is Func<X>)
        return (T) () => Resolve(typeof(X));
    return (T)Resolve(typeof(T));
}

Or to put my question another way, if I have a type T, how can I detect if it is an instance of Func<X>, and if so, what is the type of X?

Was it helpful?

Solution

take a look at this question from this morning - might give you a good start - C# generic list <T> how to get the type of T?

OTHER TIPS

I misunderstood your question.

It is impossible to do it in one function the way you're trying to because the compiler must have a delegate type to create the lambda as at compile time.

However, this should work.

public T Resolve<T>()
{
    return (T)Resolve(typeof(T));
}

public Func<T> LazyResolve<T>()
{
    return () => Resolve<T>();
}

In answer to the question in the comment, you need to invoke the lambda expression, not cast it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top