Berryl
Berryl

Reputation: 12833

Where to put InternalsVisibleTo

Related to this question is, how does the generation of the AssemblyInfo work?

I have been putting InternalsVisibleTo in the file of the first class of an assembly where I realize that it will be useful. It seems more appropriate to be in AssemblyInfo with the other assembly attributes, but I wouldn't want it to be overwritten inadvertently.

So, where should it go?

Upvotes: 31

Views: 16204

Answers (3)

Tim Lloyd
Tim Lloyd

Reputation: 38434

Assembly-level attributes can appear in any code file; however, by convention they are placed in the AssemblyInfo.cs file. This aids discoverability, as this is where people (or tools) will commonly look when investigating issues.

// AssemblyInfo.cs
[assembly: InternalsVisibleTo("YourProjectTests")]

I have been using InternalsVisibleTo for many years and placing it in the AssemblyInfo file. I have never known it to be overwritten by tools i.e. Visual Studio (all editions).

Upvotes: 27

It is 2022, and with the introduction of SDK-style projects, another option to put the InternalsVisibleTo attribute is the project file. Add the following lines to your *.csproj file:

<ItemGroup>
  <InternalsVisibleTo Include="ProjectName.Tests" />
</ItemGroup>

Another case that can be useful is to use parametric project names like that:

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>$(MSBuildProjectName).Tests</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

Not sure, but I assume you can use this feature for .NET 5+.

Lastly, I agree with @Tim Lloyd. Putting the InternalsVisibleTo attribute in a central location (either in AssemblyInfo.cs or project file) in the assembly improves discoverability and eventually this is an assembly-level attribute.

Upvotes: 74

user111013
user111013

Reputation:

AssemblyInfo is really just a way of organising your Assembly-wide attributes.

There's no reason you can't put all your code in one giant .cs file, and pass it to MSBuild. You'll get the same end result.

I've had reason to have multiple AssemblyInfo files - AssemblyInfo.cs was specific to each assembly, but CommonAssemblyInfo was shared amongst many assemblies, and contained things like Version numbers and soforth that were generated by the build system.

Upvotes: 5

Related Questions