jeudi 11 juin 2015

Activator.CreateInstance() - Constructor not found

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.

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





Aucun commentaire:

Enregistrer un commentaire