다음을 통해 공유


How to be a "good friend" to a signed assemly

Hi, here I am again fighting some signed\unsigned assembly issues. This time everything is related to the fact that we are writing a class that needs to be accessed by partners through the public methods but it needs to give some special privileges to a certain assembly. This would mean that an assembly needs to have internal access to properties+methods from another assembly (what you would have called friends classes back in the C++ days).

C# is very kind to us and it allows it by using the InternalsVisibleTo in the class that we want to be accessible from the friend "assembly":

 [assembly: InternalsVisibleTo("<Assembly_That_Is_A_Friend>")]

The only problem is that this will not work if the Assembly_That_Is_A_Friend is a signed assembly... so we need to get the public key that we used for signing it and add to the assembly name that to build the fully qualified name of the assembly.

So here are the 3 steps that you need to do to be able to befriend a signed assembly

1. From the snk file get the public key version of the signing key

 sn -p The_Signing_snk.snk OutKey.snk
 Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.

Public key written to OutKey.snk

2. From the public key file get the public key as a string of hex numbers:

 sn -tp OutKey.snk

Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.

Public key is
0024...
eff9...
451a...
369f...
59451f84

Public key token is 841...

3. Now take the full public key ans use it to refer to the assembly with the fully qualified name

[assembly: InternalsVisibleTo("<Assembly_That_Is_A_Friend>, PublicKey=<Public_Key_Of_The_Signing_snk>")] 

You should now be ready to access the internal methods\properties from the signed assembly to the assembly that you were working on while all the other partners referencing it will have access just to the rest of the properties.

This is just what "friends" are for!!!

Thanks,
Ionut