I need to get my subclasses of DataContext and I found the below function for that lying around somewhere and it sure finds my subclass but I can’t instantiate it 🙁
public static IEnumerable<T> GetSubclassesFor<T>(Assembly assembly)
{
return (assembly.GetTypes()
.Where(t => t.BaseType == (typeof (T)))
.Select(t => (T) Activator.CreateInstance(t, new object[] {"asdasd"})))
.ToList();
}
I get the following error message:
System.Reflection.TargetInvocationException
: Ett undantagsfel har inträffat i
målet för en aktivering. —->
System.TypeInitializationException :
Typinitieraren för
PlaynGO.Cashier.Data.CashierDC utlöste
ett undantag. —->
System.NullReferenceException :
Objektreferensen har inte angetts till
en instans av ett objekt. vid
System.RuntimeMethodHandle.InvokeConstructor(IRuntimeMethodInfo
method, Object[] args, ref
SignatureStruct signature, RuntimeType
declaringType) vid
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags
invokeAttr, Binder binder, Object[]
parameters, CultureInfo culture) vid
System.RuntimeType.CreateInstanceImpl(BindingFlags
bindingAttr, Binder binder, Object[]
args, CultureInfo culture, Object[]
activationAttributes) vid
System.Activator.CreateInstance(Type
type, Object[] args) vid
PlaynGO.Dbml.Reflexion.b_3(Type
t) i Reflexion.cs: line 23 vid
System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext()1..ctor(IEnumerable
vid
System.Collections.Generic.List11
collection) vid
System.Linq.Enumerable.ToList(IEnumerable
source) vid
PlaynGO.Dbml.Reflexion.GetInstances(Assembly
assembly) i Reflexion.cs: line 23 vid
PlaynGO.Dbml.UnitTests.TestReflection.TestGettingTypes()
i TestReflection.cs: line 21
–TypeInitializationException vid PlaynGO.Cashier.Data.CashierDC..ctor(String
connection)
–NullReferenceException vid PlaynGO.Cashier.Data.CashierDC..cctor()
The constructor I want to call is the following:
public CashierDC(string connection) :
base(connection, mappingSource)
MappingSource is directly instantiated and is an instance field. Where do I go wrong? What do I have to do to make this work?
PS. This is .NET 4.0
The TargetInvocationException indicates that the constructor that it is invoking has thrown an exception. Perhaps this is due to the actual value that you are passing in for the connection string. You might want to try using the debugger and set a break point in the constructor taking a connection string and (1) make sure that it is being invoked and (2) determine where the exception is occurring.