Wednesday, September 30, 2009

Strong name assembly and unit test project (InternalsVisibleTo attribute)

I tried to create a test project for a strong name assembly and I've encountered following error

Friend assembly reference 'TestProject1' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.

In order to fix it, the test project assembly has to be strong signed as well. The thing is that the test assembly needs to get access to the private members in the tested assembly, so it has to be decorated with the InternalsVisibleTo
attribute and should look like this:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TestProject1, PublicKey=PUBLIC_KEY")]

Where TestProject1 is the name of the test assembly which need access to private members, and PUBLIC_KEY is,as the name suggests, the public key value of tested assembly. But how to get the PUBLIC_KEY value?

> sn –Tp AssemblyFileName

And this information is displayed; we need the public key

Public key is

0024000004800000940000000602000000240000525341310004000001000100537d27966b492e
6e4402d93b86848897b04781de2bf54fbef46671e3163d817d43bed3a786eeaa0e5beda76cda89
ec6845deef5d2852165bac0a4df08a22bb8fccec93c4c24ed7803886178b6d4279488b7800eac0
bbfa6357e3c52d6bb19bb278056955fba5f4c85fa18164088ca18377f15d74d9b75e0fd58cd053
97cdc7de

Public key token is fd41b11fd220edb5

So the attribute at the end has this form:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TestProject1, PublicKey="+
"0024000004800000940000000602000000240000525341310004000001000100537d27966b492e"+
"6e4402d93b86848897b04781de2bf54fbef46671e3163d817d43bed3a786eeaa0e5beda76cda89"+
"ec6845deef5d2852165bac0a4df08a22bb8fccec93c4c24ed7803886178b6d4279488b7800eac0"+
"bbfa6357e3c52d6bb19bb278056955fba5f4c85fa18164088ca18377f15d74d9b75e0fd58cd053"+
"97cdc7de")]

After adding above attribute I could build without the unit test project any issues. Problem solved.

No comments: