Creating a COM object from a ProgID

Suppose you have an architecture where you expose interfaces to your clients and they can create their own COM objects to extend your application by simply implementing one of your interfaces. You don't force them to use a particular ProgID (they may have multiple objects that implement the same interface). Instead, the ProgIDs are stored somewhere (database, XML file, whatever).

You're now porting your application to .NET and still want your client's customizations to work. In your VB6 code, you currently use CreateObject and the interface to call your client's code (ProgID hard-coded for sample purposes):

Public Sub CallExtender()
    Dim oFoo    As IFoo
    
    Set oFoo = CreateObject("Client.ProgID")
    oFoo.DoSomething
End Sub

How to do the same thing in your C# .NET code? Very easy. You create your interop library for your Interfaces DLL using tlbimp and add it to your C# project. Then:

public void CallExtender()
{
	Type comType = Type.GetTypeFromProgID("Client.ProgID");
	object comObj = Activator.CreateInstance(comType);
	IFoo foo = (IFoo) comObj;
	foo.DoSomething();
}

No knowledge of the client's current COM objects (like an imported type library) is required.

No Comments