.NET Development

Module Boundaries the Compiler Enforces in .NET 10: internal, Separate Projects and InternalsVisibleTo

Team Nippysoft
• • 14 min read
Module Boundaries the Compiler Enforces in .NET 10: internal, Separate Projects and InternalsVisibleTo

In a modular monolith, the first rule is that one module doesn't reach into another's internals: Billing asks for an order's data through a contract, not by creating the classes that live inside Orders. The rule gets written in the team wiki, repeated in code reviews and, sooner or later, broken by a using added at three on a Friday afternoon. It compiles, the tests pass, and nobody notices until Orders has to move.

The C# compiler can enforce much of that rule with no extra tooling, as long as each module's boundary is a project and its implementation is internal. This guide shows how with a .NET 10 example we compiled and ran: the project layout, the real errors the compiler gives when someone crosses the boundary, how to register services without exposing types, how to test internals with InternalsVisibleTo and, above all, what the compiler doesn't cover and still needs architecture tests.

Why the boundary is the project, not the folder

internal limits access to the current assembly. In the usual layout of a .NET solution, each project compiles into its own assembly; that's why splitting modules into projects lets you use internal as a boundary. Referencing an internal type or member from another assembly is a compile error. Namespaces, on the other hand, restrict nothing: in the docs' words, "Namespaces have no access restrictions". A Modules/Orders folder inside a single project is a convention; two projects with an internal implementation are a boundary the compiler checks on every build.

This isn't a stretch for internal. The docs describe it as a common choice in component-based development, because it lets a group of components cooperate privately without being exposed to the rest of the application code. And the assembly is the unit whose manifest declares which types it exposes to the outside and which other assemblies it depends on.

Microsoft's architecture guidance starts from the same place: the smallest possible number of projects is one, and then all the logic compiles into a single assembly. Its Clean Architecture version tells compile-time dependencies apart from runtime-only ones: the UI layer works with interfaces from the application core and, ideally, doesn't know the implementation types in the infrastructure layer.

BoundaryWho enforces itWhat breaks it
Namespace or folderNobodyAny using
Project with an internal implementationThe compiler (CS0234 and CS0122)Reflection, UnsafeAccessor, a misplaced InternalsVisibleTo
References between projectsNobody: the compiler accepts themOne ProjectReference too many
Architecture testThe test pipelineAnything the rules don't spell out

The layout: one contract and one implementation per module

Each module is two projects. The contracts project is public and holds only interfaces and DTOs. The implementation project is entirely internal, except for one method that registers its services. Other modules reference only the contract.

One language detail works in your favor: a top-level type with no modifier is already internal. In the implementation project, closed is the default; public has to be typed out, and every public that shows up there deserves a question in code review. It's the encapsulation principle from Microsoft's guidance applied at the project level: each component exposes a well-defined interface and doesn't let others modify its state directly.

src/
├── Modules/
│   ├── Orders/
│   │   ├── Shop.Orders.Contracts/   IOrderQuery, OrderSummary (public)
│   │   └── Shop.Orders/             OrderRepository, Features/* (internal)
│   │                                OrdersModule.AddOrders (public)
│   └── Billing/
│       ├── Shop.Billing.Contracts/  IBilling (public)
│       └── Shop.Billing/            InvoiceGenerator (internal)
│                                    BillingModule.AddBilling (public)
└── Shop.Host/                       Program.cs
tests/
└── Shop.Orders.Tests/               xunit, sees the internals of Orders

The example's .csproj files are short because TargetFramework, Nullable and ImplicitUsings come from a Directory.Build.props at the root; without it they don't compile as shown:

<Project>
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

The Orders contract is all Billing knows about:

namespace Shop.Orders.Contracts;

public sealed record OrderSummary(int Id, decimal Total);

public interface IOrderQuery
{
    OrderSummary? Find(int id);
}

The Billing project spells that out in its references: its own contract and the Orders contract, never the Shop.Orders project. The FrameworkReference to Microsoft.AspNetCore.App brings in the dependency injection container without NuGet packages, which is the usual setup in a web monolith.

<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <ProjectReference Include="../Shop.Billing.Contracts/Shop.Billing.Contracts.csproj" />
    <!-- Billing only knows the Orders contract -->
    <ProjectReference Include="../../Orders/Shop.Orders.Contracts/Shop.Orders.Contracts.csproj" />
  </ItemGroup>
</Project>

Inside Orders, everything is internal sealed. The sealed isn't decoration: a class nobody should extend gets sealed, as we explained in C# class types in C# 14.

using Shop.Orders.Contracts;

namespace Shop.Orders.Features.Query;

internal sealed class OrderQuery(OrderRepository repository) : IOrderQuery
{
    public OrderSummary? Find(int id) =>
        repository.Total(id) is decimal total ? new OrderSummary(id, total) : null;
}
namespace Shop.Orders;

internal sealed class OrderRepository
{
    private readonly Dictionary<int, decimal> _totals = new() { [1] = 120.50m, [2] = 80m };

    public decimal? Total(int id) => _totals.TryGetValue(id, out var total) ? total : null;
}

Billing works against the interface and has no idea which class sits behind it:

using Shop.Billing.Contracts;
using Shop.Orders.Contracts;

namespace Shop.Billing;

internal sealed class InvoiceGenerator(IOrderQuery orders) : IBilling
{
    public string Invoice(int orderId) =>
        orders.Find(orderId) is { } order
            ? $"Invoice for order {order.Id}: {order.Total:0.00}"
            : $"Order {orderId} not found";
}

What the compiler rejects

Say someone in a hurry decides Billing should create the Orders query directly:

namespace Shop.Billing;

internal static class OrdersShortcut
{
    // Billing tries to use the internal implementation of Orders.
    public static object Create() =>
        new Shop.Orders.Features.Query.OrderQuery(new Shop.Orders.OrderRepository());
}

Without a reference to the implementation project, the type doesn't even exist as far as Billing is concerned:

error CS0234: The type or namespace name 'Features' does not exist in the namespace 'Shop.Orders' (are you missing an assembly reference?)
error CS0234: The type or namespace name 'OrderRepository' does not exist in the namespace 'Shop.Orders' (are you missing an assembly reference?)

The next move for someone in a hurry is to add the missing reference to Shop.Billing.csproj:

<!-- Shop.Billing.csproj: the line someone adds -->
<ProjectReference Include="../../Orders/Shop.Orders/Shop.Orders.csproj" />

Now the compiler finds the types, but they're still closed. That's the second barrier: even with the reference in place, internal stays shut.

error CS0122: 'OrderQuery' is inaccessible due to its protection level
error CS0122: 'OrderRepository' is inaccessible due to its protection level

When a CS0122 shows up between modules, there are three ways out. The right one is to grow the contract: add what Billing needs to IOrderQuery, with its own DTO. The tempting one is to make the class public, which reopens the boundary with no warning at all. The third, an InternalsVisibleTo pointing at Billing, opens the whole internal surface of Orders, not just the class that was needed. The CS0122 itself tells you the contract fell short.

The host gets the same treatment. It does reference the Orders project to call its registration method, yet a new Shop.Orders.OrderRepository() in the host gives the same CS0122. The diagram sums up which attempts get through and which don't:

Which attempts from Billing get through and which the compiler stops Billing tries to reach Orders in five ways. Using the contract interface compiles. With a ProjectReference, calling AddOrders, which is public, compiles. Without a ProjectReference, creating OrderQuery gives CS0234 at the project edge. With a ProjectReference, it gives CS0122 at the internal edge. Reflection gets in at run time because the compiler can't see it. Each attempt is drawn in order. Billing Shop.Orders.Contracts (public) Shop.Orders (project) OrdersModule.AddOrders (public) internal OrderQuery OrderRepository uses IOrderQuery compiles with ProjectReference: AddOrders compiles: it's public no ProjectReference: new OrderQuery CS0234: the type doesn't exist with ProjectReference: new OrderQuery CS0122: it's internal reflection, at run time gets in: the compiler can't see it

Registering services without exposing types

If everything is internal, how do the implementations reach the container? Each module exposes a single public method that registers them against the interfaces in its contract. Microsoft's convention for these extension methods is Add{Service}, so the Orders one is called AddOrders:

using Microsoft.Extensions.DependencyInjection;
using Shop.Orders.Contracts;
using Shop.Orders.Features.Query;

namespace Shop.Orders;

public static class OrdersModule
{
    public static IServiceCollection AddOrders(this IServiceCollection services)
    {
        services.AddSingleton<OrderRepository>();
        services.AddScoped<IOrderQuery, OrderQuery>();
        return services;
    }
}

The host wires up the application with those methods and nothing else:

using Microsoft.Extensions.DependencyInjection;
using Shop.Billing;
using Shop.Billing.Contracts;
using Shop.Orders;

var services = new ServiceCollection()
    .AddOrders()
    .AddBilling();

using var provider = services.BuildServiceProvider(
    new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true });
using var scope = provider.CreateScope();
var billing = scope.ServiceProvider.GetRequiredService<IBilling>();
Console.WriteLine(billing.Invoice(1));
Console.WriteLine(billing.Invoice(9));
Invoice for order 1: 120.50
Order 9 not found

There's one failure the compiler won't catch. The container needs a public constructor to create a service. The class can be internal, but if the constructor is too, the project compiles and fails at startup:

A suitable constructor for type 'Shop.Orders.Features.Query.OrderQuery' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

A public constructor inside an internal class exposes nothing: the class is still inaccessible outside its assembly. That's why the example uses a primary constructor, which is public. And that's why the host builds the container with ValidateOnBuild = true: the error shows up when BuildServiceProvider runs, at startup, rather than on the first request that needs the service. It arrives wrapped in an AggregateException whose message starts with "Some services are not able to be constructed". With new ServiceCollection() it defaults to false, and the generic host turns it on only in Development, so set it explicitly. Its reach is the container: it checks that every registered service can be created, not that the database answers or that an external service is up, so it doesn't replace integration tests. The docs also note that open generic services aren't validated.

Testing internals with InternalsVisibleTo

The Orders unit tests live in another assembly and need to see internals. That's what InternalsVisibleTo is for, and in an SDK-style project you declare it in the .csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <ProjectReference Include="../Shop.Orders.Contracts/Shop.Orders.Contracts.csproj" />
  </ItemGroup>
  <!-- Only the test project sees the internals of Orders -->
  <ItemGroup>
    <InternalsVisibleTo Include="Shop.Orders.Tests" />
  </ItemGroup>
</Project>

The SDK generates the attribute [assembly: InternalsVisibleTo("Shop.Orders.Tests")]; we saw it in the AssemblyInfo.cs left under obj/. InternalsVisibleTo grants access to what's internal, but it doesn't replace the reference to the assembly: Shop.Orders.Tests.csproj still references the Orders project (we've left out the ItemGroup with the Microsoft.NET.Test.Sdk, xunit and xunit.runner.visualstudio packages):

<ItemGroup>
  <Using Include="Xunit" />
  <ProjectReference Include="../../src/Modules/Orders/Shop.Orders/Shop.Orders.csproj" />
</ItemGroup>

With the reference and the attribute, the test creates the internal classes directly:

using Shop.Orders;
using Shop.Orders.Features.Query;

namespace Shop.Orders.Tests;

public class OrderQueryTests
{
    [Fact]
    public void Find_returns_the_order_total()
    {
        // OrderQuery and OrderRepository are internal: only this project can see them.
        var query = new OrderQuery(new OrderRepository());

        var order = query.Find(1);

        Assert.NotNull(order);
        Assert.Equal(120.50m, order.Total);
    }

    [Fact]
    public void Find_returns_null_when_missing()
    {
        Assert.Null(new OrderQuery(new OrderRepository()).Find(9));
    }
}

Both tests pass; without InternalsVisibleTo, the same project fails with five CS0122 errors. Three details prevent surprises:

  • It isn't transitive: if a project C references the friend assembly, C can't see the module's internals.
  • If the assembly is strong-named, the friend has to be strong-named too, and you need its full public key.
  • It covers internal, protected internal and private protected members, never private ones. In the friend assembly, a private protected member is only accessible from types that derive from its containing class.

Outside of tests, using it is a judgment call. Microsoft presents it for unit tests and for class libraries whose additions live in separate assemblies, and there it's legitimate: they're parts of the same component. The catch is its reach: the friend assembly sees every internal type and member, not one class. Between two modules of the same application that opens up the whole implementation, and nothing in Billing's code shows it; that's why a bigger contract is usually the cheaper option there.

What the compiler doesn't cover

The compiler closes off crossings between modules, but not everything. We confirmed the first four gaps in the same example; the fifth doesn't depend on the code:

  1. Two slices in the same project. If Orders is organized as vertical slices inside one project, internal doesn't separate them. The query slice uses an internal type from the register slice, and it compiles:
using Shop.Orders.Features.Register;

namespace Shop.Orders.Features.Query;

internal static class CrossSliceShortcut
{
    // Two slices in the same project: Query uses Register's internal type, and it compiles.
    public static RegisterOrderRequest Copy(int id) => new(id, 0m);
}
  1. The reference itself. The compiler doesn't stop Billing from adding the ProjectReference to Shop.Orders; it only stops it from using what's internal. With that reference, calling OrdersModule.AddOrders, which is public, compiles just fine. And the reference doesn't have to be direct: project references are transitive by default. If Billing references a shared project that in turn references Shop.Orders, the first barrier falls without touching Billing's .csproj: in the example, crossing.cs went from CS0234 to CS0122 and AddOrders compiled. With the MSBuild property DisableTransitiveProjectReferences set to true, CS0234 came back. Even so, unwanted references, direct or indirect, are better guarded by an architecture test.
  2. Reflection. The compiler checks access at compile time, and the runtime also rejects a direct call to an inaccessible member with MethodAccessException, but reflection skips that check. At run time, the host loaded OrderRepository through reflection and got IsPublic=False, Total(2)=80. Modern .NET has no sandbox that blocks that access: code access security (CAS) is no longer treated as a security boundary. UnsafeAccessor also reaches inaccessible members. None of this is a security flaw: the compiler just can't see what happens at run time.
  3. Extra public surface. If someone leaves a public type in the implementation, the compiler doesn't warn. Rule CA1515 suggests making public types internal, but by default it only looks at executable assemblies and is off in .NET 10. Its output_kind option extends it to libraries, though it then also flags the registration class, which has to stay public.
  4. Shared data. internal decides which types each assembly can see, not which tables it touches. Even if every module keeps its implementation internal, nothing stops two modules from reading or writing the same tables. Splitting projects doesn't isolate data. Microsoft's microservices guide describes the traditional approach as a single database shared across all services and asks each service to own its data; in a modular monolith, that rule comes from the team, not the compiler.

One example sums up the limit: if a module leaves its infrastructure types public, such as a repository, and another module uses them through the ProjectReference, it compiles without a warning, even though the architecture says it should only see the contract. It's the same thing we saw with AddOrders: with the reference, everything public compiles. The compiler protects visibility, not every architecture decision.

Where architecture tests come in

First, the compiler: it closes off crossings between modules with no configuration, on every build, on every developer's machine. Then, architecture tests for what's left: slices inside one project, references between projects that shouldn't exist, and naming conventions. Tools such as NetArchTest, ArchTestNet or ArchGuard.NET let you write those rules as tests that run in the pipeline.

An architecture test warns in the pipeline; the compiler warns in the editor, before the commit. The more the compiler covers, the shorter and steadier the rules get, and the less they depend on namespaces following a convention.

A checklist for reviewing a module

  1. Is it its own project, separate from its contract?
  2. Is the only public surface the contract plus the Add{Module} method?
  3. Does each InternalsVisibleTo point to its test project or to another part of the same component, and was it a deliberate decision?
  4. Do the services it registers have public constructors, and does the host use ValidateOnBuild?
  5. Is there an architecture test for what the compiler can't see: slices, references (indirect ones too) and names?

Frequently asked questions

Isn't one namespace per module enough?

No. Namespaces have no access restrictions: inside the same project, any class can use any other with a using. The boundary the compiler enforces is the assembly; in the usual layout, the project.

Do I need two projects per module, or is one enough?

.NET doesn't require it: it's an architecture decision for a stricter boundary. One project with public contracts and an internal implementation is also valid: the internal part stays closed. What you lose is that other modules reference that project and see everything public in it, not just the contract. With two, the contracts project separates what a module promises from how it delivers, and the rest of the application depends only on the promise.

Can I use InternalsVisibleTo between two modules?

You can, and it's worth weighing case by case. The friend module sees the other's whole internal surface, not just the class it needed, so between modules it weakens the boundary. It fits better in tests or between assemblies of the same component or library; if one module needs something specific from another, the usual move is to add it to the contract.

Does this work the same in .NET 11?

We tested it on .NET 10 (SDK 10.0.403), the current stable LTS release. .NET 11 is still a release candidate, and we didn't test with it.

Conclusion

An architecture rule written in a wiki depends on the whole team's memory. The same rule expressed as separate projects and internal types gets checked by the compiler on every build, with clear errors: CS0234 when the reference is missing and CS0122 when someone adds it. The cost is one contracts project per module and one registration method; the payoff is that the Friday-afternoon shortcut doesn't compile.

To start, take the module with the most incoming dependencies, move its contract into its own project, mark its implementation internal and build the solution. Every error that shows up is a crossing that already existed. Whatever the compiler can't see, leave to an architecture test.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code