vicker313 tech blog

February 28, 2010

How to Allow Access of Internal Class in Another .Net Assembly

Filed under: .Net — Tags: , , , — vicker313 @ 8:00 am

We always create separate assemblies so that we can reuse some of the classes, and declare the classes as public so that can be accessed by other assemblies. However this will allow other people to use the assemblies that we created. To protect our assemblies to be assessed by our owned assemblies only, we can declare the classes as internal and do the following setup:

For the assembly that will access your shared assembly

  1. Use SN utility to create a new key pair and save it in an out put file (key.snk). SN is available in .Net SDK.
    sn -k key.snk
  2. Use your .Net IDE (either Visual Studio or Sharpdevelop) to sign the assembly with the key file (key.snk).
  3. Compile the assembly.
  4. Use SECUTIL to extract the strong name information from the assembly (usually in the bin\debug directory in you project folder) in hex string format and save it to a text file (strong.txt). SECUTIL is also available in .Net SDK.
    secutil -hex -s application.exe > strong.txt
  5. Inside the strong name file (strong.txt), you can see a long hex string, copy it (remember to exclude the first 2 character 0x)

For the shared assembly

  1. Use SN utility to create a another key pair and save it in an out put file (key1.snk).
    sn -k key1.snk
  2. Use your .Net IDE (either Visual Studio or Sharpdevelop) to sign the assembly with the key file (key1.snk).
  3. Open AssemblyInfo.cs, (or AssemblyInfo.vb, depend on the language that you used)
  4. Be sure System.Runtime.Compiler.Services is imported:
    using System.Runtime.CompilerServices;
  5. Go to last line of the file, add the following line (ProgramName is the name of you referring assembly and hexstring is the hex string that you copied from the strong name file just now)
    [assembly: InternalsVisibleTo("ProgramName, PublicKey=hexstring")]
  6. Compile the assembly.

Now you should able to refer the shared assembly and use the internal classes.

You might not need to install SDK to get SN or SECUTIL, try google around should able to find some download links.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: