I’m running into a generics issue while working on a generic Dependency Injection handler (a base Service Locator).
Edit 1 (for clarity)
Okay so I’m actually using SimpleInjector as a DI resolver and it has the class constraint on it’s GetInstance method, so here is some more complete code:
public T GetInstance<T>() where T : class
{
try
{
// works
return _container.GetInstance<T>();
}
catch( ActivationException aEx )
{
return default( T );
}
}
public T GetInstance<T>()
{
try
{
if( typeof( T ).IsClass )
{
// does not work, T is not a reference type
return _container.GetInstance<T>();
}
}
catch( ActivationException aEx )
{
return default( T );
}
}
Edit 2 – final code since it looks strange in comments:
public T GetInstance<T>()
{
try
{
if( typeof( T ).IsClass )
{
return (T) _container.GetInstance(typeof(T));
}
}
catch( ActivationException aEx )
{
return default( T );
}
}
You can use one more helper method? please find test class below