Search code examples
ninjectinversion-of-controlioc-containersimple-injector

Simpleinjctor get instance based on generic type


I need to convert Ninject to SimpleInjector Implementation.

I have the following code

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

I want the equivalent to this for simple injector

I have tried

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

But this throws an error due to T not being a class as it is a generic type.

I can't cast the method to strictly take and return T as class because it is an interface implementation.

Any Advice?


Solution

  • Either add a generic type constraint to your Resolve method:

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

    or call the non-generic GetInstance overload:

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