Simpleinjctor 基于泛型获取实例

Simpleinjctor get instance based on generic type

我需要将 Ninject 转换为 SimpleInjector 实现。

我有以下代码

public T Resolve<T>()
{
    // IKernel kernel - is the global declaration
    return kernel.Get<T>();
}

我想要与此等效的简单注入器

我试过了

public T Resolve<T>()
{
    // SimpleInjector.Container kernel - is the global declaration
    return kernel.GetInstance<T>();
}

但这会引发错误,因为 T 不是 class,因为它是泛型。

我无法将方法强制转换为严格 take and return T as class 因为它是一个接口实现。

有什么建议吗?

向您的 Resolve 方法添加泛型类型约束:

public T Resolve<T>() where T : class
{
    return kernel.GetInstance<T>();
}

或调用非泛型 GetInstance 重载:

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