views:

197

answers:

1

I'm using Ninject 1.0 and would like to be able to inject lazy initialisation delegates into constructors. So, given the generic delegate definition:

public delegate T LazyGet<T>();

I'd simply like to bind this to IKernel.Get() so that I can pass a lazy getter into constructors, e.g.

public class Foo
{
    readonly LazyGet<Bar> getBar;

    public Foo( LazyGet<Bar> getBar )
    {
        this.getBar = getBar;
    }
}

However, I can't simply call Bind<LazyGet<T>>() because it's an open generic type. I need this to be an open generic so that I don't have to Bind all the different lazy gets to explicit types. In the above example, it should be possible to create a generic delegate dynamically that invokes IKernel.Get<T>().

How can this be achieved with Ninject 1.0?

A: 

Don't exactly understand the question, but could you use reflection? Something like:

// the type of T you want to use
Type bindType;
// the kernel you want to use
IKernel k;

// note - not compile tested
MethodInfo openGet = typeof(IKernel).GetMethod("Get`1");
MethodInfo constGet = openGet.MakeGenericMethod(bindType);

Type delegateType = typeof(LazyGet<>).MakeGenericType(bindType);
Delegate lazyGet = Delegate.CreateDelegate(delegateType, k, constGet);

Would using lazyGet allow you to do what you want? Note that you may have to call the Foo class by reflection as well, if bindType isn't known in the compile context.

thecoop
Thanks for the code, but it's "naked" - you don't show how this is registered with Ninject. I can easily write code like you did, but how do I tell Ninject to bind that so that when it creates an instance of a type that takes a lazy delegate, it binds it to its own Get method?What I'm doing seems pretty clear to me: I want to bind the parameter to Ninject's own Get method, so that when the object requests the instance of the type, it calls Ninject's Get.
Mike Scott