Passing class objects in different versions of an assembly

The scenario is as follows:

  • I have the assembly "MyAssembly". The "IMyInterface" interface is defined in this assembly.
  • In the same assembly, I have one class (MyClass) with a method that defines it as:

public void MyMethod (IMyInterface object) {}

  • Now, in my project, I created an interface with the same name and exact properties that were opened by the IMyInterface interface in MyAssembly.
  • I have a class that extends this interface (the one I created in my project), and I want to pass an object of this class as a parameter to the "MyMethod" method in another assembly using reflection.

The problem is

  • When I try to call a method using reflection, I got this exception: "Unable to convert object to IMyInterface type" .

The code -

Assembly myAssembly = Assembly.LoadFrom("MyAssembly");
object classObject = myAssembly.CreateInstance("MyClass");
Type classType = myAssembly.GetType("MyClass");
MethodInfo myMethod = classType.GetMethod("MyMethod", BindingFlags.Instance);

// Creating an object of class in the latest assembly and need to pass this
// to method in assembly with different version.
ClassExtendingMyInterface obj= new ClassExtendingMyInterface ();

myMethod.Invoke(classObject, new object[] { obj});

If I understand correctly, this is because the created object is in a different assembly, and the parameter expected by the method has its own assembly.

Another approach that I was thinking about was to create my own dynamic method in the class that will take an object of my class.

I tried to find google and through Reflection.Emit or RunSharp to dynamically create my own class. But we can only use this in our dynamically generated assemblies, but we cannot create dynamic methods or a class in an existing assembly.

, - . . .

+3
3

-, "Identity Type", DLL Hell .NET. , , . , , [AssemblyVersion], [AssemblyCulture], PublicKeyToken () ProcessorArchitecture. "real" Type.AssemblyQualifiedName. System.String, , System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

, . , , .

, .NET 4. , COM, , [Guid] . PIA " ". , .

+6

:

, "IMyInterface" "MyAssembly".

; . ; CLR, .

reference . .

+1

, , , . , SAME Interface:

dll MyInterfaces:

namespace MyInterfaces
{
    public interface IMyInterface
    {
        void SharedMethod();
    }
}

DLL, MyInterfaces. , "using" :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyInterfaces;

namespace MyFirstProject
{
    public class MyClass1
    {
        public void MyMethod(IMyInterface SomeObject) { }
    }
}

Now I believe that your creation of a dynamic object should work, since both objects implement the same interface defined in "MyInterfaces".

+1
source

All Articles