.Net 当同一程序集的两个版本加载到一个 AppDomain 中时是否存在潜在问题?
当两个版本之间发生重大更改时,我们提出了一种处理向后兼容性的策略。我们在当前AppDomain中加载以前版本的程序集,用旧版本类型反序列化一些数据,然后将它们转换为新版本中的等效数据。
- 这种方法有什么我应该注意的陷阱吗?
- 如果我在省略程序集版本时尝试通过反射加载类型,会发生什么情况,如果当前 AppDomain 中存在该类型的两个版本,它是否总是加载该类型的最新版本?
编辑:
这是问题#2的场景,
这两个程序集加载在同一个AppDomain中:
MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089
MyAssembly, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089
两个程序集都定义类型 MyAssembly.MyType
。
那么,如果某些代码使用这种反射:
Type t = Type.GetType("MyAssembly.MyType, MyAssembly, Culture=neutral, PublicKeyToken=b17a5c561934e089");
此调用是否会确定返回 MyAssembly.MyType, MyAssembly, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089
?
我想如果我在反序列化同一程序集的两个加载版本中存在的类型时使用 BinaryFormatter.AssemblyFormat = FormatterAssemblyStyle.Simple ,也会发生相同的情况。
We've come up with a strategy to handle backward compatibility when there is a breaking change between two versions. We load the previous version assemblies in the current AppDomain, deserialize some data with the old version types and then convert these into their equivalent in the new version.
- Are there any pitfalls with this approach that I should be aware of?
- What would happen if I try to load a type by reflection when its assembly version is omitted, will it always load the latest version of the type if two version of it exists in the current AppDomain?
Edit:
Here is an scenario of question #2,
These two assemblies are loaded in the same AppDomain:
MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089
MyAssembly, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089
Both assembly define the type MyAssembly.MyType
.
Then if some code use this kind of reflection:
Type t = Type.GetType("MyAssembly.MyType, MyAssembly, Culture=neutral, PublicKeyToken=b17a5c561934e089");
Will this call deterministically return MyAssembly.MyType, MyAssembly, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089
?
I guess the same scenario would occur if I use BinaryFormatter.AssemblyFormat = FormatterAssemblyStyle.Simple
when deserializing types that exists in two loaded version of the same assembly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将假设您使用 Assembly.LoadFile() 来工作。反射不会真正给你带来麻烦,它需要一个程序集引用来让事情顺利进行。当您的代码决定使用哪个程序集引用时,它就处于控制之中。显然,如果您想从旧版本加载类型,则需要从先前调用 LoadFile() 获得的文件。
LoadFile() 调用不能扰乱任何其他程序集解析,程序集在没有加载上下文的情况下加载。
I'll work from the assumption that you use Assembly.LoadFile(). Reflection cannot really get you into trouble, it needs an Assembly reference to get the ball rolling. Your code is in control when it decides what Assembly reference to use. Clearly, you'll need the one you got from a previous call to LoadFile() if you'd want to load a type from the old version.
The LoadFile() call cannot otherwise mess up any other assembly resolves, the assembly is loaded without a loading context.