【问题标题】:Simpleinjctor get instance based on generic typeSimpleinjctor 获取基于泛型类型的实例
【发布时间】:2016-03-14 01:58:33
【问题描述】:

我需要将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 不是一个类,因为它是一个泛型类型。

我不能将方法强制转换为严格将T 作为类返回,因为它是一个接口实现。

有什么建议吗?

【问题讨论】:

    标签: ninject inversion-of-control ioc-container simple-injector


    【解决方案1】:

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

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

    或调用非泛型 GetInstance 重载:

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

    【讨论】:

    • 我会试试第二个
    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多