How to make internals visible to multiple other assemblies in .NET Standard
Asked Answered
P

2

9

I have multiple assemblies which include unit tests 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 additional assemblies 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?

Parados answered 19/9, 2022 at 14:41 Comment(1)
does this #14354657 answer your question?Proteose
I
18

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).

Isaiasisak answered 19/9, 2022 at 14:44 Comment(0)
S
4

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() {
    //...
  }
}
Scabies answered 19/9, 2022 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.