如何使用“InternalsVisibleTo"具有强命名程序集的属性? [英] How to use "InternalsVisibleTo" attribute with Strongly named assembly?

查看:39
本文介绍了如何使用“InternalsVisibleTo"具有强命名程序集的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用InternalsVisibleTo"属性和程序集来向我的单元测试项目公开内部方法/类.

I am using the "InternalsVisibleTo" attribute with an assembly to expose the internal methods/classes to my unit test project.

我现在需要将该程序集安装到 GAC 中,所以我需要给它一个强名称.当我尝试这样做时,我在 Visual Studio 中收到以下错误.

I now need to install that assembly into the GAC, so I need to give it a strong name. When I try doing that, I get the following error in Visual Studio.

强名称签名程序集必须在其 InternalsVisibleTo 声明中指定公钥

Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations

一点谷歌搜索把我带到了下面的文章:

A bit of Googling brought me to the article below:

https://msdn.microsoft.com/en-us/library/bb763089.aspx

本文指出:

确定强命名朋友程序集的公钥."

"Determine the public key for the strong-named friend assembly."

本文不说如何确定公钥.在哪里可以找到程序集的公钥?另外,一旦我有了公钥,这是否是声明属性的正确方法?

This article does not say how to determine the public key. Where do I find the public key for the assembly? Also, once I have the public key, would this be the correct way to declare the attribute?

[assembly: InternalsVisibleTo("Namespace.Assembly.Example.Name, PublicKey=ThePublicKey")]

推荐答案

要将 InternalsVisibleTo 与强签名程序集一起使用,您的朋友"程序集也必须强签名.测试程序集的公共令牌需要指定为 InternalsVisibleTo 值的一部分.

To use InternalsVisibleTo with strongly signed assembly your "friends" assemblies must be strongly signed too. Public token of the test assembly need to be specified as part of InternalsVisibleTo value.

请注意,该属性不用于编译时对程序集的实际验证 - 它仅指定运行时检查(以及朋友程序集的编译时检查)应验证该身份.因此,如果您只是需要编译您的主程序集,您可以指定任何公钥标记(例如,来自 Microsoft 程序集的一个,例如在您的 Web.Config 中的所有程序集引用中找到的).

Note that the attribute is not used for actual validation of assembly at compile time - it only specifies that run-time checks (and compile-time checks for friend's assembly) should validate that identity. So if you just need to compile your main assembly you can specify any public key token (i.e. one from Microsoft's assemblies as found on all assembly references in your Web.Config for example).

通常,因为您将签署程序集,所以您会知道公钥.IE.如果您有 snk 文件,则 sn -t youSnk.snk 将显示公钥.或者您可以按照 在 Visual Studio 中获取程序集的公钥令牌 以配置您的 VS 以显示任何使用 的程序集的公共令牌sn -Tp {path to assembly} 从程序集中获取公钥.(如果文档已消失,步骤将复制到此问题的其他答案)

Generally since you'll be signing assemblies you'd know the public key. I.e. if you have snk file than sn -t youSnk.snk would show the public key. Or you can follow steps in Getting Public Key Token of Assembly Within Visual Studio to configure your VS to show public token for any assembly which uses sn -Tp {path to assembly} to get public key from the assembly. (If document is gone steps are copied to the other answer to this question)

这篇关于如何使用“InternalsVisibleTo"具有强命名程序集的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆