comregasmcomvisible

.net COMVisible/ComInterop - can you use a type without registering it?


My first attempts at this have failed but I'm hoping it is possible. If I have a class like this that is COM registered:

[ComVisible(true)]
public interface Resolver
{
    object Resolve(string type);
}

[ProgId("ClassResolver")]
[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
[Guid("53DB4409-0827-471D-94CE-2601D691D04C")]
public class Class1:Resolver
{
    public object Resolve(string type)
    {
        return (ClassLibrary2.Interface1) new ClassLibrary2.Class1();
    }
}

Can I use it to return Class2.Interface1 which is ComVisible but not registered (it's in a different library):

[ComVisible(true)]
public interface Interface1
{
    string SomeMethod();
}


public class Class1:Interface1
{
    public string SomeMethod()
    {
        MessageBox.Show("SomeMethod");
        return "SomeMethod";
    }
}

My first attempts have returned the error: IUnknown:SomeMethod (No exported method), but I'm hoping there might be some trick to doing this that I don't know.


Solution

  • I found this is possible if you mark the class as ComVisible (just the interface as ComVisible wasn't enough). I can now use ClassLibrary3 via COM. See below code:

    namespace ClassLibrary1
    {
    [ComVisible(true)]
    public interface Resolver
    {
        object Resolve(string type);
    }
    
    [ProgId("ClassResolver2")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComVisible(true)]
    [Guid("83720331-12CB-48E1-947C-2413F7B9AB89")]
    public class Class1:Resolver
    {
        public object Resolve(string type)
        {
            return new ClassLibrary3.Class1();
        }
    }
    }
    

    Totally separate library that was not "Regasm"ed:

    namespace ClassLibrary3
    {
    
    [ComVisible(true)]
    public class Class1 
    {
        public string SomeMethod()
        {
            MessageBox.Show("ClassLibrary3.Class1.SomeMethod....");
            return "ClassLibrary3.Class1.SomeMethod";
        }
    }
    }