[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

microsoft.public.dotnet.framework.sdk

InvalidCastException. Confused. Please Help

MikeHanson

1/12/2003 12:53:00 AM

I am using reflection to create a type
(StudentProfileService) from a string read from an XML
config file. The type implements an interface
(IStudentProfileService). Yet, when I attempt to cast the
type (created via reflection to the interface), I get an
InvalidCastException. PLEASE HELP!!! The code is below:

///
///This is the interface
///
public interface IStudentProfileService
{
void doSomething();
}

///
///This class implements the Interface which essentially
makes it an IStudentProfileService type
///
public class StudentProfileService : IStudentProfileService
{
public void doSomething() {}
}


///This is the class that reads the XML file loads the
types and provides a lookup of the type by interface name.
public class ServiceFactory
{
///
///Reads and XML Config file and Loads the
Implementation classes from the Assembly and
//Saves them to an ArrayList.
///
private void LoadTypes( Assembly p_assembly, XmlElement
p_elem )
{
//Traverse the runtime element to load all defined
Services.
foreach( object obj in p_elem.ChildNodes )
{
if( obj is XmlElement )
{
XmlElement currElement = (XmlElement)obj;
if( currElement.Name.Equals("Type") )
{
string strTypeName = currElement.Attributes
["impl"].InnerText;
object objType = p_assembly.CreateInstance
(strTypeName, true); //Loads the implementation
StudentProfileService
if( objType != null)
m_listTypes.Add(objType); //Saves the
implementation instance to a list.
}
}
}
}


///
///Called by Clients to look up a Service implementation
that implements the passed interface type to return the
///previously loaded object.
///
public object GetService(Type p_typeService)
{
string strServiceType = p_typeService.ToString();
object objService = m_hashServices[strServiceType];
if (objService == null)
{
foreach( object obj in m_listTypes )
{
Type typeFound = obj.GetType().GetInterface
(strServiceType);
if ( typeFound != null )
{
if( strServiceType.Equals( typeFound.ToString
() ) )
{
m_hashServices[strServiceType] = obj;
objService = obj;
break;
}
}
}
}

return objService; //Returns StudentProfileService
instance.
}
} //End fo the ServiceFactory class

///
///In a Client program I call the ServiceFactory to get
the loaded object and cast it to the appropriate interface
type
///This is where I get the InvalidCastException. What am
I missing?
///
IStudentProfileService service = (IStudentProfileService)
ServiceFactory.Instance.GetService( typeof
(IStudentProfileService) );