Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activator.CreateInstance failing with 'No parameterless constructor'

Tags:

c#

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?

like image 564
sonicblis Avatar asked May 11 '26 19:05

sonicblis


1 Answers

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);
        }
    }
}
like image 73
M.Babcock Avatar answered May 14 '26 09:05

M.Babcock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!