Search code examples
c#vbscriptconstructorcomcreateobject

Call non-default constructor of COM class


I have a DLL (written in C#) containing a class with 2 Constructors; a default (no arguments) constructor, and another one with 3 arguments.

In VBscript, I want to call the second constructor, but CreateObject only receives a classValue parameter, no possible arguments parameters.

I guess the underlying implementation of CreateObject uses the system's CoCreateObject function, which according to this answer does not support arguments, but on the other hand there's QTP/UFT's DotNetFactory that is capable of such thing, so there must be a way to do it in pure VBscript.

(I want to avoid the obvious init method solution if possible).

Any ideas for how to call my non-default constructor?


Solution

  • COM does not support passing arguments to a constructor. The underlying object factory method (IClassFactory::CreateInstance) does not accept arguments.

    The workaround is pretty simple, all problems in software engineering can be solved by another level of indirection :) Just create your own factory method. You can write one that takes the arguments that the constructor needs. Roughly:

    [ComVisible(true)]
    public interface IFoo {
       //...
    }
    
    class Foo : IFoo {
       public Foo(int a, string b) { ... }
       //...
    }
    
    [ComVisible(true)]
    public class FooFactory {
        public IFoo CreateInstance(int a, string b) {
            return new Foo(a, b);
        }
    }
    

    And your VBScript can now call FooFactory's CreateInstance() method to get your class object created. Otherwise a very common pattern in COM object models, Microsoft Office automation is a very notable example.