我正在使用 Ninject 1.0,并希望能够将惰性初始化委托(delegate)注入(inject)构造函数。因此,给定通用委托(delegate)定义:
public delegate T LazyGet<T>();
我只是想将它绑定(bind)到 IKernel.Get() 以便我可以将惰性 getter 传递给构造函数,例如
public class Foo
{
readonly LazyGet<Bar> getBar;
public Foo( LazyGet<Bar> getBar )
{
this.getBar = getBar;
}
}
但是,我不能简单地调用
Bind<LazyGet<T>>()
因为它是一个开放的泛型类型。我需要这是一个开放的泛型,这样我就不必将所有不同的惰性获取绑定(bind)到显式类型。在上面的例子中,应该可以动态创建一个调用 IKernel.Get<T>()
的通用委托(delegate)。 .Ninject 1.0 如何实现这一点?
最佳答案
不完全理解这个问题,但你可以使用反射吗?就像是:
// 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);
将使用
lazyGet
让你做你想做的事?请注意,如果 bindType
,您可能还必须通过反射调用 Foo 类。在编译上下文中不知道。
关于delegates - 使用 Ninject 进行惰性泛型委托(delegate)初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2334383/