Instantiating a Class in the Assembly


Once you have a reference to a loaded assembly, you can create an instance of a class in the assembly. The only problem is that the function that lets you do this has a return type of object. Of course it needs to use object as its return type since you can use the function to create any class. However, this doesn't help us much, since we can only make calls for methods in the object class. We could cast the variable to a more concrete type, but in order to do a cast we need to have the type defined ahead of time, and that means we need to have a reference to the assembly containing the type. Having a reference to the assembly sort of defeats the whole purpose of loading an assembly dynamically. The answer to this is to use interfaces. The sample application uses this approach. It puts the definitions for the interfaces in a separate DLL. Then the Web application has a reference to the interface DLL. When we load an assembly dynamically and create an object, we can cast the object to the interface type. This makes it possible for us to use the object through the interface methods.

To create an instance of a class in an assembly:

  1. First make sure that the class implements an interface you define. Put the interface definition in a separate DLL, and reference this DLL from both the class project and the client project.

  2. Type ISomeInterface var = (ISomeInterface)ad.CreateInstance("classname"); where ISomeInterface is an interface that the class implements, var is the name of the variable that will hold the reference to the object, ad is the variable that points to the assembly you loaded dynamically, and "classname" is the name of the class plus the namespace ( Figure 12.13 ).

    Figure 12.13 CreateInstance takes in a class name and creates an instance of the class. Remember that the full name of the class includes the namespace name.
     //using System.Reflection; Assembly ad = Assembly.LoadFrom(@"ordersMemory.DLL"); ICustomerMgr var = (ICustomerMgr)ad.  CreateInstance  ( "ordersMemory.CustomerMgrMem"); 

graphics/tick.gif Tip

  • The tricky part with CreateInstance is that people (me included) often forget that the class name isn't just the short name you give to the class but also the namespace name. And as you may know already, the C# wizards by default put your classes inside of a name space with the name of your project.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net