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
public class Test
{
public T GetInstance<T>() where T : class
{
return (T)GetInstance(typeof(T));
}
private object GetInstance(Type type)
{
return Activator.CreateInstance(type);
}
public T GetEvenMoreGenericInstance<T>()
{
if( !typeof( T ).IsValueType )
{
return (T)GetInstance(typeof(T));
}
return default( T );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With