Results 1 to 9 of 9

Thread: Instantiate a class by its type name??

  1. #1

    Thread Starter
    Frenzied Member MerrionComputin's Avatar
    Join Date
    Apr 2001
    Location
    Dublin, Ireland
    Posts
    1,616

    Instantiate a class by its type name??

    OK - I have a plug in framework where my application can have 3rd party plug-ins added via the .config file (provided they confrom to the IPlugIn interface...)

    What I have so far reads the Type Name and checks if it supports the interface OK - but how do I instantiate an object of that type if it does?

    I have.....
    App.config
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
       <configSections>
          <!-- Extra custom configuration sections -->
          <section name="printerEventListeners" 
    type="PrinterMonitorService.CustomConfigurationSectionReaders.PrinterEventListenersSectionReader" />
         
       </configSections>
        
        <printerEventListeners>
           <!-- Key = the unique name by which the listener is known,
                ClassType = the full type name of the class implementing IPrinterEventListenerBase ,
                CommandLine = startup parameters for that class -->
           <printerEventListener key="printerEventListener1" 
               classType="PrinterMonitorService.PrinterMonitorLogfileListener"
               commandLine="c:\printerEventListener1.log" />
        </printerEventListeners>
    Then in the application....
    VB Code:
    1. For Each PrintJobListener In PrintJobListeners
    2.                 If PrintJobListener.ImplementingClassType.IsSubclassOf(GetType(PrintJobMonitorListenerBase)) Then
    3.                     '\\ Add an instance of the PrintJobMonitorListenerBase derived class...
    4.                     If ApplicationTracing.TraceVerbose Then
    5.                         Trace.WriteLine("PrintJobMonitorListenerBase derived class: " & PrintJobListener.ImplementingClassType.ToString, Me.GetType.ToString)
    6.                         '<-- What to put here ????
    7.                     End If
    8.                 End If
    9.             Next

    Thanks in advance,
    Duncan
    ----8<---------------------------------------
    NEW - The .NET printer queue monitor component
    ----8<---------------------------------------
    Now with Examples of use

  2. #2
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    Well, im going to need some code like that shortly, so Im sure if you dont have an answer by then, I will be helping..

  3. #3
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    You can use Activator.CreateInstance if you have the full namespace or 'type' of the object you can also use reflection via the Assembly.LoadFrom method. You can also load a type via a string using Type.GetType("MyNamespace.ObjectTypeName") Sorry for such a brief post but I'm headed out the door.

  4. #4
    Addicted Member PeteD's Avatar
    Join Date
    Jun 2003
    Location
    Sydney
    Posts
    158
    yep... something like this:

    VB Code:
    1. Imports System.Reflection
    2.  
    3. 'Then use
    4.  
    5.       Dim a As [Assembly] = [Assembly].Load("YourDllProject")
    6.  
    7.       T = a.GetType("YourDllProject.MainForm", True)
    8.  
    9.       'Create an instance of the form
    10.       Dim o As Object = Activator.CreateInstance(t)
    11.  
    12.       'Show the form
    13.      Dim mainForm As Form = CType(o, Form)
    14.      mainForm.Show()

  5. #5
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    Ok... So if I have a tabpageclass named "AdditionalInfo", this should work (but it doesn't)
    VB Code:
    1. Dim o As Object =  Activator.CreateInstanceFrom("ReportExecHelper.AdditionalInformationTabPageClass.vb", "TabPage")
    2.  myTabPage = CType(o, TabPage)

    This is the error I get:

    An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll

    Additional information: File or assembly name ReportExecHelper.AdditionalInformationTabPageClass, or one of its dependencies, was not found.


    So I switched the original line with this ..
    VB Code:
    1. Dim o As Object = Activator.CreateInstanceFrom("ReportExecHelper.dll", "AdditionalInformationTabPageClass")

    And got this...

    An unhandled exception of type 'System.TypeLoadException' occurred in mscorlib.dll

    Additional information: Could not load type AdditionalInformationTabPageClass from assembly ReportExecHelper, Version=1.0.1370.15851, Culture=neutral, PublicKeyToken=null.


    So what gives? All i want to do is create an instance of the object using its Name ... i.e. CreateInstance("MyForm1")

  6. #6
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    You have to use the full namespace of the object:

    Dim o As Object = Activator.CreateInstanceFrom("ReportExecHelper.dll", "RootOrOtherNamespaceHere.ObjectName")

    I think you also might need to use the full path of the assembly.
    Last edited by Edneeis; Oct 2nd, 2003 at 11:31 AM.

  7. #7
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    Yea... I don't know,I can't get it to work.

    Does this only work with class libraries? (.dll's)?

    So if I made a test project with two forms, I couldn't possibly call the second form using .CreateInstanceFrom("Form2")

  8. #8
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Actually I pulled some old code where I used this and if you use CreateInstanceFrom or CreateInstance with the assemblyname parameter then it returns an ObjectHandle which can be used in remoting (and maybe other ways too) instead of the actual object. If you were to use that you'd have to unwrap it as the type that it is, but like I said I don't know if that is specific to remoting or not. If you just want to dynamically load something try this:
    VB Code:
    1. 'load assembly via the path
    2.         Dim asm As Reflection.Assembly = Reflection.Assembly.LoadFrom("E:\Code\NET\Practice\TestBed6\bin\TestBed6.exe")
    3.         'load the type from the assembly via the full namespace
    4.         Dim obj As Object = Activator.CreateInstance(asm.GetType("TestBed6.Form5"))
    5.         DirectCast(obj, Form).ShowDialog()

    And no it doesn't have to be a dll.

  9. #9
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    I got it to work finally.

    VB Code:
    1. Dim ty As Type = Type.GetType("ReportExecHelper.AdditionalInformationTabPageClass")
    2.             myobj = Activator.CreateInstance(ty)
    3.             TabControl1.TabPages.Add(CType(myobj, TabPage))

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width