Home > Software design >  How to make internals visible to multiple other assemblies in .NET Standard
How to make internals visible to multiple other assemblies in .NET Standard

Time:09-20

I have multiple assemblies which include UnitTests for a single .NET Standard 2.0 project. To thoroughly test my project I want the internal classes to be visible to both assemblies.

Here is the part of my .csproj file which makes the internals visible to one assembly:

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

How can I add multiple parameters to this configuration?

Right now it works with either one of the 2 values that I need but I haven't figured out how to make it work for both at the same time. This should be possible, as I have found solutions for this in .NET and .NET Framework, but not .NET Standard.

Any Suggestions?

CodePudding user response:

Just add a second AssemblyAttribute block, like:

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

In the sample above, Other.Assembly.Name stands for the name of the other assembly (omitting directory path and extension).

CodePudding user response:

The InternalsVisibleTo attribute, placed at the beginning of the source code file or in your project's AssemblyInfo file, can be used numerous times to allow more than one external assembly access. This assumes all assemblies are unsigned.

For signed assemblies, you'll need to include the full public key following the friend assembly name when calling the attribute (both in one string as a single parameter).

using System.Runtime.CompilerServices;

// one for each friend assembly
[assembly:InternalsVisibleTo("Assembly1")]
[assembly:InternalsVisibleTo("Assembly2")]

// or, using alternate syntax
[assembly:InternalsVisibleTo("Assembly3"), InternalsVisibleTo("Assembly4")]

public class MyClass {
  // visible to all the assemblies listed above
  internal static void MyMethod() {
    //...
  }
}
  • Related