How do I create and use a .NET metadata-only 'Reference Assembly'?

天涯浪子 提交于 2019-11-28 05:52:48

To create a reference assembly, you would add this line to your AssemblyInfo.cs file:

[assembly: ReferenceAssembly]

To load others, you can reference them as usual from your VisualStudio project references, or dynamically at runtime using:

Assembly.ReflectionOnlyLoad()

or

Assembly.ReflectionOnlyLoadFrom()


If you have added a reference to a metadata/reference assembly using VisualStudio, then intellisense and building your project will work just fine, however if you try to execute your application against one, you will get an error:

System.BadImageFormatException: Cannot load a reference assembly for execution.

So the expectation is that at runtime you would substitute in a real assembly that has the same metadata signature.

If you have loaded an assembly dynamically with Assembly.ReflectionOnlyLoad() then you can only do all the reflection operations against it (read the types, methods, properties, attributes, etc, but can not dynamically invoke any of them).


I am curious as to what your use case is for creating a metadata-only assembly. I've never had to do that before, and would love to know if you have found some interesting use for them...

If you are still interested in this possibility, I've made a fork of the il-repack project based on Mono.Cecil which accepts a "/meta" command line argument to generate a metadata only assembly for the public and protected types.

https://github.com/KarimLUCCIN/il-repack/tree/xna

(I tried it on the full XNA Framework and its working afaik ...)

Yes, this is new for .NET 4.0. I'm fairly sure this was done to avoid the nasty versioning problems in the .NET 2.0 service packs. Best example is the WaitHandle.WaitOne(int) overload, added and documented in SP2. A popular overload because it avoids having to guess at the proper value for *exitContext" in the WaitOne(int, bool) overload. Problem is, the program bombs when it is run on a version of 2.0 that's older than SP2. Not a happy diagnostic either. Isolating the reference assemblies ensures that this can't happen again.

I think those reference assemblies were created by starting from a copy of the compiled assemblies (like it was done in previous versions) and running them through a tool that strips the IL from the assembly. That tool is however not available to us, nothing in the bin/netfx 4.0 tools Windows 7.1 SDK subdirectory that could do this. Not exactly a tool that gets used often so it is probably not production quality :)

You might have luck with the Cecil Library (from Mono); I think the implementation allows ILMerge functionality, it might just as well write metadata only assemblies.

I have scanned the code base (documentation is sparse), but haven't found any obvious clues yet...

YYMV

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