Reflection Question?

Reflection Question?

Old forum URL: forums.lhotka.net/forums/t/845.aspx


RangerGuy posted on Tuesday, August 08, 2006

Hi Everyone,

I'm trying to use reflection against one of our BO's which inherits from ReadOnlyRoot. I get the following error

An unhandled exception of type 'System.MissingMethodException' occurred in mscorlib.dllAdditional information: No parameterless constructor defined for this object.

When it reaches the following code in bold. I'm confused with this error because all Csla BO's are defined with a parameterless constructor.

foreach (ModuleMoin myModules)
{
 if (Mo.Name == ModuleName)
 {
 Type[] myTypes = Mo.GetTypes();
 foreach (Type Ty in myTypes)
 {
  if (Ty.Name == TypeName)
  {
   MethodInfo[] myMethodInfo = Ty.GetMethods(flags);
   foreach (MethodInfo Mi in myMethodInfo)
   {
    if (Mi.Name == MethodName)
    {
     
Object obj = Activator.CreateInstance(Ty);
     Object response = Mi.Invoke(obj, null);
    }
   }
  }
 }
 }
}

PS (I borrowed this code from another website to try and understand how to work with reflection)

RockfordLhotka replied on Tuesday, August 08, 2006

Oh, I am so disappointed!!! Another web site??  Wink [;)]

The answers you seek are in Chapter 4 in the server-side data portal - in SimpleDataPortal to be exact. There's an overload that allows you to tell .NET to use the default ctor even if it is non-public. You do still need a default ctor, but it can be something other than public.

RangerGuy replied on Wednesday, August 09, 2006

my bad! Sorry Rocky LOL!

Thanks again Sir your a live saver! I'll check that out today. I'm going to re-read chapter 4 :)

RangerGuy replied on Wednesday, August 09, 2006

Just wanted thank you for pointing me in the right direction. I just re-read chapter 4 :) and found the answer!

Incase anybody is interested. If your going to use reflection to create an instance of an object with a private constructor like we do with Csla.net. Then you need to use the System.Activator class like the following:

obj = Activator.CreateInstance(objectType, true);

This tells .NET to create the instance even if the constructor is not public :)

 

Thank you again Rocky!

U ROCK! (no pun intended LOL!)

Copyright (c) Marimer LLC