locked
Activator.GetObject with Reflection

    Question

  • I need to dynamically load an interface assembly that I use on client-side remoting. Something like this.

    static void Main(string[] args)
    {
      TcpClientChannel clientChannel = new TcpClientChannel();
      ChannelServices.RegisterChannel(clientChannel, false);
    
      Assembly interfaceAssembly = Assembly.LoadFile("RemotingInterface.dll");
      Type iTheInterface = interfaceAssembly.GetType("RemotingInterface.ITheService");
    
      RemotingConfiguration.RegisterWellKnownClientType(iTheInterface, "tcp://localhost:9090/Remotable.rem");
      object wellKnownObject = Activator.GetObject(iTheInterface, "tcp://localhost:9090/Remotable.rem");
    }
    

    Only I can't seem to grasp how to call any methods as I can't cast the Activator.GetObject. How can I create a proxy of ITheService without knowing the interface at compile-time? I can't cast the Activator.GetObject to an interface because I don't know the interface at compile-time. The type of wellKnownObject is MarshalByRefObject.

    Tuesday, May 17, 2011 5:46 PM

Answers

  • Hi,

    As you do not have the physical interface, you will need to invoke the method using reflection

     MethodInfo m = iTheInterface.GetMethod("MethodName");
          m.Invoke(wellKnownObject, new object[] { "Argument"});
    

    If you are using c# 4.0, you can use the new dynamic keyword to late bind the object.

    dynamic wellKnownObject = Activator.GetObject(iTheInterface, "tcp://localhost:9090/Remotable.rem");
    wellKnownObject.SomeExistingMethod("test");
    

    • Marked as answer by Rubio Monday, May 23, 2011 8:57 AM
    Tuesday, May 17, 2011 6:40 PM

All replies

  • Hi,

    As you do not have the physical interface, you will need to invoke the method using reflection

     MethodInfo m = iTheInterface.GetMethod("MethodName");
          m.Invoke(wellKnownObject, new object[] { "Argument"});
    

    If you are using c# 4.0, you can use the new dynamic keyword to late bind the object.

    dynamic wellKnownObject = Activator.GetObject(iTheInterface, "tcp://localhost:9090/Remotable.rem");
    wellKnownObject.SomeExistingMethod("test");
    

    • Marked as answer by Rubio Monday, May 23, 2011 8:57 AM
    Tuesday, May 17, 2011 6:40 PM
  • Thanks. The reflection method works. I was a little confused as to how I can map the object to the interface.

    However, the dynamic method doesn't work. It will throw a RuntimeBinderException.

    Monday, May 23, 2011 9:00 AM