I'm creating a method that will use CastleWindsor to try to resolve a type, but use a default type if the component isn't configured (so I don't have to configure everything until I actually want to change the implementation). Here's my method...
public static T ResolveOrUse<T, U>() where U : T
{
try
{
return container.Resolve<T>();
}
catch (ComponentNotFoundException)
{
try
{
U instance = (U)Activator.CreateInstance(typeof(U).GetType());
return (T)instance;
}
catch(Exception ex)
{
throw new InvalidOperationException("IOC Couldn't instantiate a '" + typeof(U) + "' because: " + ex.Message);
}
}
}
When a WebConfigReader is passed in as the default type to use, I get the error "No parameterless constructor defined for this object". Here's my WebConfigReader class...
public class WebConfigReader : IConfigReader
{
public string TfsUri
{
get { return ReadValue<string>("TfsUri"); }
}
private T ReadValue<T>(string configKey)
{
Type type = typeof(T).GetType();
return (T)Convert.ChangeType(ConfigurationManager.AppSettings[configKey], type);
}
}
Since I have no ctor, it should work. I've added a paramless ctor and I've passed in true as the second param to CreateInstance and none of the above worked. I can't figure out what I'm missing. Any thoughts?
typeof(U) will already return the type U represents. Doing the extra GetType() on it will return the type System.Type which doesn't have a default constructor.
So your first code block could be written as:
public static T ResolveOrUse<T, U>() where U : T
{
try
{
return container.Resolve<T>();
}
catch (ComponentNotFoundException)
{
try
{
U instance = (U)Activator.CreateInstance(typeof(U));
return (T)instance;
}
catch(Exception ex)
{
throw new InvalidOperationException("IOC Couldn't instantiate a '" + typeof(U) + "' because: " + ex.Message);
}
}
}
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