15.10 Expose a .NET Component Through COM


Problem

You need to create a .NET component that can be called by a COM client.

Solution

Create an assembly that follows certain restrictions identified in this recipe. Export a type library for this assembly using the Type Library Exporter (Tlbexp.exe) command-line utility.

Discussion

The .NET Framework includes support for COM clients to use .NET components . When a COM client creates a .NET object, the CLR creates the managed object and a COM callable wrapper (CCW) that wraps the object. The COM client interacts with the managed object through the CCW. The runtime creates only one CCW for a managed object, regardless of how many COM clients are using it.

Types that need to be accessed by COM clients must meet certain requirements:

  • The managed type (class, interface, struct, or enum) must be public .

  • If the COM client needs to create the object, it must have a public default constructor. COM doesn't support parameterized constructors.

  • The members of the type that are being accessed must be public instance members. Private , protected , internal , and static members are not accessible to COM clients.

In addition, you should consider the following recommendations:

  • It is recommended that you don't create inheritance relationships between classes, because these relationships will not be visible to COM clients (although .NET will attempt to simulate it by declaring a shared base class interface).

  • It is recommended that the classes you are exposing implement an interface. For added versioning control, you can use the attribute System.Runtime.InteropServices.GuidAttribute to specify the GUID that should be assigned to an interface.

  • Ideally, you should give the managed assembly a strong name so that it can be installed into the GAC and shared among multiple clients.

In order for a COM client to create the .NET object, it requires a type library (a .tlb file). The type library can be generated from an assembly using the Tlbexp.exe command-line utility. Here's an example of the syntax you use:

 tlbexp ManagedLibrary.dll 

Once you generate the type library, you can reference it from the unmanaged development tool. With Visual Basic 6, you reference the .tlb file from the Project/References dialog. In Visual C++ 6, you can use the #import statement to import the type definitions from the type library.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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