Createting instance of interface in host in VSTA Add-in

Last post 07-24-2008, 11:56 AM by Melody. 1 replies.
Sort Posts: Previous Next
  •  07-24-2008, 11:11 AM 1209

    Createting instance of interface in host in VSTA Add-in

    How to create instance of interface in host in VSTA Add-in

    I have an interface in host application. I want create an instance in Add-in [Visual Basic]. Is there any way?

    I tried

    Dim obj As New IMyInterface

    but it requires two argument

    global::System.AddIn.Contract.IContract

    and 

    global::Microsoft.VisualStudio.Tools.Applications.TypeInfrastructureManager

     

    How to get these instances in Add-in vb file?


    Nitin Umap
    Software Professional
    Filed under:
  •  07-24-2008, 11:56 AM 1210 in reply to 1209

    Re: Createting instance of interface in host in VSTA Add-in

    nitinumap,
    There are two issues here:

    1) 
    >Dim obj As New IMyInterface
    You cannot create an instance of an interface, instead you can declare a variable of the interface's type and set it to an instance of a class that implements the interface.

    Dim obj As IMyInterface = New ClassThatImplementsTheInterface


    2)
    Vsta add-ins should use a factory method to get a host object instead of creating an instance.  This is so that all objects are created on the host side and marshaled across through the proxy layer instead of relying on the add-in to provide management for the object. 

    Below is some code that shows how to do this on the host and add-in side.  For more information on this, you may want to check out our EventSample which demonstrates how to implement this. 

    I hope this helps, please let me know if you have any questions.
    Thanks,
    -Melody

    'Host (Application class)

    Public Function getIMyInterface() As IMyInterface
       Dim obj As IMyInterface = New ClassThatImplementsTheInterface
       Return obj
    End Function

    Public Class ClassThatImplementsTheInterface
      Implements IMyInterface
    End Class

    Public Interface IMyInterface
    End Interface

    'Add-in
    Private Sub AppAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup

        'create a new object using the factory method
        Dim iObj As IMyInterface = Application.getIMyInterface("hello")

    End Sub

View as RSS news feed in XML