简体   繁体   中英

Call local .NET (2) COM+ component from C# application

I've created a .NET 2 COM+ component to be consumed by our archaic classic ASP website. This is done quite simply in classic ASP...

Dim MenuManager : Set MenuManager = Server.CreateObject("MenuManager.MenuManager")

However, I want to performance profile the component using a C# console application.

How do I call this from within the C# console application?

You are using late binding with the CreateObject() function. You want to steal, beg or borrow a copy of VS2010 to use the C# 4.0 dynamic keyword to make that easy to do. Here's similar code that works on any machine. It uses late binding to create the FileSystemObject COM component, the first two lines are equivalent to your code snippet. It lists the subdirectories of the c:\windows folder:

using System;

class Program {
    static void Main(string[] args) {
        var type = Type.GetTypeFromProgID("Scripting.FileSystemObject");
        dynamic obj = Activator.CreateInstance(type);
        dynamic win = obj.GetFolder("c:/windows");
        foreach (dynamic subwin in win.SubFolders) {
            Console.WriteLine(subwin.Name);
        }
        Console.ReadLine();
    }
}

If you can't use C# version 4 then consider using VB.NET instead. It has the same syntax and also has a CreateObject() function.

To call a native code COM object from C# you'd select Add Reference and then select the COM tab and use it to add a reference to your COM object's type library. That would run TLBIMP to import your type library and generate a nice set of wrappers and types for the COM object. Then you would just use those types and wrappers to instantiate your COM object and call its methods.

This won't work for COM objects implemented using managed code. The TLBIMP tool notices that the type library was generated from managed code and refuses to import it. Instead it suggests that you just add a .NET reference to the assembly.

You might be able to build a set of COM wrappers by hand as described here . But that seems like an awful lot of work when you could use the much more straightforward solution suggested by @Hans

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM