Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create an instance of because Type.ContainsGenericParameters is true

enter image description here

I am creating an instance dynamically using reflection.

var typesTR = Assembly.GetAssembly(typeof(BGenericConfigurationClass<>)).GetTypes()
            .Where(type =>
                    !string.IsNullOrEmpty(type.Namespace) &&
                    (type.Namespace == "EntitiesConfiguration"))
            .Where(type => type.BaseType != null
                           && type.BaseType.IsGenericType
                           &&
                           (type.BaseType.GetGenericTypeDefinition() == typeof(BGenericConfigurationClass<>) ||
                            type.BaseType.GetGenericTypeDefinition() == typeof(CGenericConfigurationClass<>) ));

foreach (var type in typesTR)
{

    dynamic configurationInstance = Activator.CreateInstance(type);
    modelBuilder.Configurations.Add(configurationInstance);
}

enter image description here

and my exception is following :- "Cannot create an instance of CGenericConfigurationClass`1[T] because Type.ContainsGenericParameters is true."

like image 610
rana laique ahmed Avatar asked Oct 28 '17 12:10

rana laique ahmed


1 Answers

It looks like one of the types in typesTR is a generic type and you are attempting to create an instance of that type without specifying the generic type parameters. As an example, this is as if you were attempting to create an instance of List<> but without providing the type between the angle brackets <>. This is not possible, Activator.CreateInstance() must be given a "closed generic type".

To do this, you could do something like the following, but based on your example, I don't think this will be very useful since you need to create numerous configuration instances and you may not know what generic type to pass in.

var t = type.MakeGenericType(typeof(SomeClassToBeUsedAsGenericTypeParameter));
dynamic configurationInstance = Activator.CreateInstance(t);
...

My guess is that typesTR has more types in it than you were expecting and includes one of the base classes which is generic. I think it should only include DClass and EClass, but is including one of the base classes.

like image 141
kmc059000 Avatar answered Sep 18 '22 09:09

kmc059000