Cannot create an instance of because Type.ContainsGenericParameters is true

c# entity-framework-6 generics

Question

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."

1
3
10/28/2017 6:45:05 PM

Popular Answer

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.

5
10/28/2017 1:18:07 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow