Loading the same Assembly twice but with different version

。_饼干妹妹 提交于 2019-12-11 00:13:49

问题


I have one assembly that is called asm.dll.

This assembly has the version 1.0.0.0 (set within AssemblyInfo.cs)

Then I need do do some code modifications in that assembly (still asm.dll), advance the version to 2.0.0.0 and build it again.

Now, I have two files named asm.dll that differ with respect to some code modifications and a their version number.

How do I load these two files during runtime?

ADDENDUM:

Right now I am trying the following:

var asm1 = Assembly.LoadFrom("dir1\asm.dll");
var asm2 = Assembly.LoadFrom("dir2\asm.dll");

var types1 = asm1.GetTypes();
var types2 = asm2.GetTypes();

Type type1 = types1.First<Type>(t => t.Name.Equals("myClassIWantToInstantiate"));
Type type2 = types2.First<Type>(t => t.Name.Equals("myClassIWantToInstantiate"));

MyObject myObject1 = (MyObject1)Activator.CreateInstance(type, new object[] { });
MyObject myObject2 = (MyObject2)Activator.CreateInstance(type, new object[] { });

But I get the following behavior:

  • the first call to Activator.CreateInstance(...) correctly returns the requested instance for myObject1

  • the second call to Activator.CreateInstance(...) returns again myObject1 instead of myObject2

  • The code compiles and the program runs without exception or observable problems, except that I do not get myObject2

I am aware of this answer and I think the code I used, is the same, only a bit newer (correct me, if I am wrong).


回答1:


In your answer, you are using Activator.CreateInstance for both objects - this is using whatever is registered globally. I believe the types loaded from the specific assemblies will not be enough to do this.

In the answer you linked, the assemblies are loaded using Assembly.LoadFile rather than LoadFrom, and CreateInstance is called on the assembly instance, rather than using the static Activator.CreateInstance. Have you tried this?

var asm1 = Assembly.LoadFile("dir1\asm.dll");
var asm2 = Assembly.LoadFile("dir2\asm.dll");

MyObject myObject1 = (MyObject)asm1.CreateInstance("myClassIWantToInstantiate");
MyObject myObject2 = (MyObject)asm2.CreateInstance("myClassIWantToInstantiate");


来源:https://stackoverflow.com/questions/35032240/loading-the-same-assembly-twice-but-with-different-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!