Activator.CreateInstance() - Constructor not found

3.8k views Asked by At

I have the following class:

internal class MyQueryTranslator : ExpressionVisitor, IExpressionTranslator<QueryRequest>
{

       private IReflectionManager _reflectionManager;

       internal MyQueryTranslator(IReflectionManager reflectionManager)
       {
           this._reflectionManager = reflectionManager;
       }

       //....
}

Meanwhile, in another class, I am trying to instantiate this class using Activator.CreateInstance() method:

internal class MyPersistenceStrategy<E> : IAsyncPersistenceStrategy<E>
     where E : class, IPersistableEntity
{

       private IReflectionManager _reflectionManager;
       private static readonly Dictionary<Type, Type> _translators;

       static MyPersistenceStrategy()
       {
             _translators = new Dictionary<Type, Type>()
             {
                  { typeof(QueryRequest), typeof(MyQueryTranslator) }
             }
       }

       private T TranslateExpression<T>(Expression expression)
       {
            if(_translators.ContainsKey(typeof(T))
                   throw new InvalidOperationException(String.Format("There is no translator for: {0}", typeof(T).Name);

            IExpressionTranslator<T> translator = 
                       (IExpressionTranslator<T>)Activator.CreateInstance(_translators[typeof(T)],
                                               BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                                               null,
                                               _reflectionManager,
                                               null);

            return translator.Translate(expression);
       }

       //...

}

However, I am getting the following error:

An unhandled exception of type System.MissingMethodException occured in mscorlib.dll
Additional information: Constructor on type XXXXX.MyQueryTranslator not found

As you can see, I am passing the appropiate BindingFlgs so the constructor can be actually found.

The TranslateExpression<T> method is being called like this:

QueryRequest request = TranslateExpression<QueryRequest>(expression);

I should also note that both classes are in the same assembly.

1

There are 1 answers

0
Robot Mess On

As some have pointed out it is matching the wrong overload. The parameters must be an array of objects.

(IExpressionTranslator<T>)Activator.CreateInstance(_translators[typeof(T)],
                                           BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                                           null,
                                           new object[] { _reflectionManager },
                                           null);