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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With