delegates - 使用 Ninject 进行惰性泛型委托(delegate)初始化

标签 delegates lazy-loading generics ninject

我正在使用 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/

相关文章:

c# - 使用反射在 C# 中引发事件的单元测试

java - Hibernate:拉取所有惰性集合的最佳实践

javascript - Angular 2 SystemJS 延迟加载捆绑问题

typescript - 在 TypeScript 中扩展另一种类型的任何类型的参数?

java - Java 中 String 列表和 String[] 列表,或 T 列表和 T[] 列表的通用方法

swift - 从 AnyIterator 获取 RawRepresentable 的通用数组

ios - danielgindi/iOSCharts chartValueSelected 未调用

c# - 在某些异步操作之后使用委托(delegate)作为回调是否正确?

c# - 将函数(带参数)作为参数传递?

.net - 我可以使用 ADO.Net Entity Framework 延迟加载标量属性吗?