Archive for June, 2008|Monthly archive page

How to Access Nonpublic Types of a Referenced Assembly

Most of the solutions I work with consist of at least 3 projects: data access layer, business logic layer, windows app, etc. Each of those projects contains at least a few instances of code that throws exceptions. Typically, these exceptions are used to indicate invalid parameters or internal errors that cannot be handled locally. I tend to use resource files to store assembly messages because it allows me to enforce a common exception message format.

In small and medium-sized solutions, the number of exception messages in the resource file is small: (15-20) and they are not very likely to be reused. Large solutions (5+ projects), on the other hand, often contain 50+ messages and messages are likely to be reused. The logical thing to do, in this case, is to put all exception messages in a separate assembly (ProjectName.FeatureName.Resources) and reference it.

This sounds like an easy thing to do and it is. Except for one minor issue… The designer.cs file generated by the Visual Studio resource editor is marked internal and so are it’s members. It is possible to edit the file manually to change resource visibility to public, but these changes are lost the moment you edit the file using the designer because it re-generates the designer.cs file.

There is a little known attribute in the .NET Framework that helped me get around this problem: InternalsVisibleTo.

This attribute makes all nonpublic types in an assembly it is applied to visible to another assembly.

Example: AssemblyInfo.cs


[assembly:InternalsVisibleTo(“ProjectName.FeatureName.Services, PublicKey=2e049ab9234d98234“)]

The first line specifies that all nonpublic types are visible to assembly ProjectName.FeatureName.Data (version and culture of the assembly are not taken into account).

The second line specifies that all nonpublic types are visible to assembly ProjectName.FeatureName.Services that has public key 2e049ab9234d98234.