How can we use .NET components in COM
.NET components can't be used in straight forward way with the COM. You will require to create CCW in order to communicate COM components with .NET assemblies. Following are some of the different approaches to implement it :-
1)Explicitly declare interfaces
Public Interface ICustomer
Property CustomerName() As String
Property CustomerCode() As String
Public Class Customer
Private PstrCustomerName As String
Private PstrCustomerCode As String
Public Sub AddCustomer() Implements ICustomer.AddCustomer Try
' addin of database code can go here
Catch ex As Exception
Public Property CustomerCode() As String Implements
Set(ByVal value As String)
PstrCustomerCode = value
Public Property CustomerName() As String Implements ICustomer.CustomerName
Set(ByVal value As String) PstrCustomerName = value
Public Sub New()
The above customer class is going to be used by COM components so all the properties and methods are declared in interface and implemented in the customer class.Customer Name.Customer Code & AddCustomer are Ist declared in ICustomer & then implemented in the Customer Class. Please Note that the class must have a default constructor.
2)The second way to generate CCW is by using InteropServices attributes. In this interfaces are created automatically.
Following are the different type of class attributes :
None:-No class interface is generated for class. This is the default setting when you do not specify anything.
AutoDispatch :- Interface that supports IDispatch is created for class. However, no type information is generated.
AutoDual :- A dual interface is created for the class. Type information is generated and made available in the type library.
Below are the source code we have used the third attribute.
_ Public Class ClsCompliant
Other than class attributes defined up there are some other attributes with which you can govern other part of the assembly. For Example "GuidAttribute" allows you to specify the GUID, "ComVisibleAttribute" can be used to hide .NET types from COM etc.
a)When .NET assembly is created using either interface or by using interopservices method we need to create a COM type library using Type library export tool.
b)The final thing is registering the CCW in registry by using regasm tool.
regasm AssemblyName [Options]
c)Finally refer the TLB in your COM IDE Below is figure showing VB6 IDE referencing the DLL