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

查看:209
本文介绍了如何使用"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.

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

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会显示公钥.或者,您可以按照此问题的其他答案)

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天全站免登陆