Start Debugging

NetArchTest HaveDependencyOn: why it fails on an assembly you reference, and what it actually detects

NetArchTest checks type-level dependencies by namespace, not assembly references, and Should() applies the rule to every type. A 15-case .NET 11 repro shows which usages NetArchTest.Rules 1.3.2 and eNhancedEdition 1.4.5 detect, which they miss (consts, nameof, typeof in attributes), and how BannedApiAnalyzers covers the gap.

This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process

Short answer: NetArchTest never looks at assembly references. It walks the IL of every type with Mono.Cecil and matches the full names of the types each one touches against the namespaces you pass, segment by segment. So HaveDependencyOn("Spms.Infrastructure") means “has a dependency on some type whose namespace is Spms.Infrastructure or below”, and because it sits after Should(), the rule must hold for every type in the assembly. Most types in an API project never touch Infrastructure, so the test fails even though the project reference is there. Use That().HaveDependencyOn(...).GetTypes() and assert the list is not empty instead. Namespace-level rules (NotHaveDependencyOnAny("Spms.Infrastructure.Mail", ...)) do work, but only for usages that survive into IL: const values, nameof, typeof(...) inside attribute arguments, and types that only pass through an allowed API are invisible. Everything below was run on .NET 11 (SDK 11.0.100) with NetArchTest.Rules 1.3.2, NetArchTest.eNhancedEdition 1.4.5, and Microsoft.CodeAnalysis.BannedApiAnalyzers 5.6.0.

The question this answers is NetArchTest does not detect direct assembly dependency or namespace dependency as expected. The asker has a layered ASP.NET Core solution (Spms.Api, Spms.Application, Spms.Domain, Spms.Infrastructure, Spms.Persistence) and wants two rules: the API project may call Spms.Infrastructure.Configuration (the AddInfrastructure() registration method), but must not use Spms.Infrastructure.Mail, .Options, .ActionFilter, .FileSystem, or .DocumentGeneration directly. The existing answer correctly says the check is type-level, then asks how the second test misbehaves. This post reproduces both tests and measures exactly where the line is.

Should() means every type, not “at least one”

This is the test from the question:

// .NET 11, NetArchTest.Rules 1.3.2 -- fails
var result = Types
    .InAssembly(ApiAssembly)
    .Should()
    .HaveDependencyOn(InfrastructureAssembly.GetName().Name)
    .GetResult();

Two things are going on. First, the string is not an assembly name to NetArchTest. It happens to equal the root namespace of the Infrastructure project, so it works as a namespace prefix, but if the assembly were called Spms.Infra and its namespaces were Spms.Infrastructure.*, passing the assembly name would match nothing at all.

Second, and this is what actually fails the test: NetArchTest has two halves. That() starts a predicate that filters the type list. Should() starts a condition that every remaining type must satisfy, and GetResult() reports the types that do not. So the test above asserts “every single type in Spms.Api uses a type from Spms.Infrastructure”. In the repro, 6 of the 17 types in the API assembly fail that, which is the expected outcome for any real project:

Should().HaveDependencyOn("Spms.Infrastructure"): IsSuccessful=False, failing=6 of 17
   failing: Spms.Api.Cases.C01_UnusedUsing
   failing: Spms.Api.Cases.C04_Const
   failing: Spms.Api.Cases.C05_Nameof
   failing: Spms.Api.Cases.C06_AttributeTypeofArgument
   ...

The fix is to flip from condition to predicate and assert on the selection:

// .NET 11, C# 15, xunit.v3 4.0.4, NetArchTest.Rules 1.3.2
[Fact]
public void Api_uses_Infrastructure_somewhere()
{
    var dependents = Types.InAssembly(ApiAssembly)
        .That()
        .HaveDependencyOn("Spms.Infrastructure")
        .GetTypes();

    Assert.NotEmpty(dependents);
}

In the repro this returns 11 types, including the compiler-generated Program class that holds the top-level statements calling builder.Services.AddInfrastructure(). That one call is enough for the rule to pass.

If what you really want is an assembly-level check, use reflection, but know its limit. The C# compiler only writes an AssemblyRef for an assembly whose types or members the compiled IL actually references, so a ProjectReference alone does not put it there. A console app that references Spms.Infrastructure but only reads a const and a nameof from it prints this from typeof(Program).Assembly.GetReferencedAssemblies():

System.Runtime, System.Console, System.Linq

No Spms.Infrastructure. “The API must reference Infrastructure” is therefore a weak rule in either tool, and usually not one worth enforcing. The rule that matters is the negative one.

How NetArchTest matches a namespace

NotHaveDependencyOnAny takes strings that “can be namespaces or specific types”, per the XML docs in Conditions.cs. Internally they go into a NamespaceTree that splits on ., :, / and +, so matching is by whole segment, not by string.StartsWith. That matters for sibling namespaces with a shared prefix. In the repro, Spms.Infrastructure.MailTemplates is a separate namespace, and a type that only uses MailTemplates.Templates.Welcome(...) is not flagged by the rule for Spms.Infrastructure.Mail. That is the behavior you want, and it means you do not need trailing dots or other tricks.

The dependency scan itself lives in TypeDefinitionCheckingContext.cs. For each type it checks the base type, implemented interfaces, generic constraints, fields, properties, events, method signatures, local variable types, the attribute types on all of those, and the operands of every IL instruction: type tokens, the declaring type of each field or method referenced, and the generic arguments of generic method calls. Compiler-generated nested types (closure classes, async state machines) are scanned as part of their parent. Generic arguments are followed recursively, so IOptions<SmtpOptions> counts as a dependency on SmtpOptions.

What it does not inspect is just as specific. Custom attributes are checked only through ca.AttributeType, so constructor arguments such as typeof(AuditFilter) are never read. Method references are checked only through their declaring type, so the return type of a method you call is not a dependency unless you then do something with it. And anything the C# compiler folds away before IL (const, nameof, using directives) does not exist for a tool that reads IL.

The 15-case repro

To get numbers instead of guesses, the repro has an Spms.Infrastructure class library with five namespaces and an Spms.Api web project with one class per way of touching them. Abridged:

// Spms.Infrastructure, .NET 11, C# 15
namespace Spms.Infrastructure.Mail
{
    public interface IMailSender { Task SendAsync(string to, string body); }
    public sealed class SmtpMailSender : IMailSender { public Task SendAsync(string to, string body) => Task.CompletedTask; }
    public static class MailDefaults { public const string FromAddress = "noreply@spms.local"; }
}
namespace Spms.Infrastructure.MailTemplates
{
    public static class Templates { public static string Welcome(string name) => $"Hi {name}"; }
}
namespace Spms.Infrastructure.Options
{
    public sealed class SmtpOptions { public string Host { get; set; } = ""; }
}
namespace Spms.Infrastructure.ActionFilter
{
    public sealed class AuditFilter : IActionFilter { /* empty OnActionExecuting / OnActionExecuted */ }
}
namespace Spms.Infrastructure.Configuration
{
    using Spms.Infrastructure.Mail;
    public static class InfrastructureRegistration
    {
        public static IServiceCollection AddInfrastructure(this IServiceCollection services)
            => services.AddSingleton<IMailSender, SmtpMailSender>();
        public static IMailSender CreateMailer() => new SmtpMailSender();
    }
}
// Spms.Api, .NET 11, C# 15
using Microsoft.AspNetCore.Mvc;
using Spms.Infrastructure.ActionFilter;
using Spms.Infrastructure.Configuration;
using Spms.Infrastructure.Mail;
using Spms.Infrastructure.MailTemplates;
using Spms.Infrastructure.Options;

namespace Spms.Api.Cases;

public class C01_UnusedUsing { public int Value => 42; }
public class C02_CtorParameter(IMailSender sender) { public IMailSender Sender => sender; }
public class C03_MethodBody { public Task Run() { IMailSender s = new SmtpMailSender(); return s.SendAsync("a", "b"); } }
public class C04_Const { public string From() => MailDefaults.FromAddress; }
public class C05_Nameof { public string Name() => nameof(SmtpMailSender); }
[ServiceFilter(typeof(AuditFilter))]
public class C06_AttributeTypeofArgument : ControllerBase { }
public class C07_GenericArgument(Microsoft.Extensions.Options.IOptions<SmtpOptions> options) { public string Host => options.Value.Host; }
public class C08_Lambda { public Func<IMailSender> Factory() => () => new SmtpMailSender(); }
public class C09_Async { public async Task Run(IServiceProvider sp) { await Task.Yield(); var s = (IMailSender)sp.GetService(typeof(IMailSender))!; await s.SendAsync("a", "b"); } }
public class C10_ThroughAllowedApiCalled { public Task Run() => InfrastructureRegistration.CreateMailer().SendAsync("a", "b"); }
public class C11_ThroughAllowedApiPassed { public object Run() => InfrastructureRegistration.CreateMailer(); }
public class C12_PrefixSibling { public string Run() => Templates.Welcome("x"); }
public class C13_TypeofInBody { public Type Run() => typeof(SmtpOptions); }
[TypeFilter(typeof(AuditFilter))]
public class C14_TypeFilterAttribute : ControllerBase { }
public class C15_AllowedOnly { public IServiceCollection Run(IServiceCollection s) => s.AddInfrastructure(); }

The harness ran the question’s second rule, then checked each class on its own:

// .NET 11, C# 15, NetArchTest.Rules 1.3.2
string[] forbidden =
[
    "Spms.Infrastructure.ActionFilter", "Spms.Infrastructure.DocumentGeneration",
    "Spms.Infrastructure.FileSystem", "Spms.Infrastructure.Mail", "Spms.Infrastructure.Options",
];

foreach (var t in Types.InNamespace("Spms.Api.Cases").GetTypes().OrderBy(t => t.Name))
{
    bool hit = Types.InAssembly(api).That().HaveNameStartingWith(t.Name)
        .And().HaveDependencyOnAny(forbidden).GetTypes().Any();
    Console.WriteLine($"{t.Name,-32} {(hit ? "DETECTED" : "missed")}");
}

The same project was then run with NetArchTest.eNhancedEdition 1.4.5 (the maintained fork; its API renames a few members, for example FailingTypes instead of FailingTypeNames and ResideInNamespace instead of Types.InNamespace), and compiled once more with Microsoft.CodeAnalysis.BannedApiAnalyzers 5.6.0 and a BannedSymbols.txt that bans the three namespaces the cases touch. Results:

CaseHow the API touches a forbidden namespaceNetArchTest.Rules 1.3.2eNhancedEdition 1.4.5BannedApiAnalyzers 5.6.0 (RS0030)
C01using directive onlymissedmissednot flagged
C02Constructor parameter typedetecteddetectednot flagged
C03Local variable, new, method calldetecteddetectedflagged (new and call)
C04Reads a constmissedmissedflagged
C05nameof(SmtpMailSender)missedmissednot flagged
C06[ServiceFilter(typeof(AuditFilter))]missedmissedflagged
C07IOptions<SmtpOptions> parameterdetecteddetectedflagged (the .Host access)
C08Only inside a lambdadetecteddetectedflagged
C09Inside an async methoddetecteddetectedflagged
C10Forbidden type returned by an allowed API, then calleddetecteddetectedflagged
C11Forbidden type returned by an allowed API, only passed onmissedmissednot flagged
C12Sibling namespace MailTemplatesnot flagged (correct)not flagged (correct)not flagged (correct)
C13typeof(SmtpOptions) in a method bodydetecteddetectedflagged
C14[TypeFilter(typeof(AuditFilter))]missedmissedflagged
C15Only Spms.Infrastructure.Configurationnot flagged (correct)not flagged (correct)not flagged (correct)

The two NetArchTest packages agree on every row. eNhancedEdition does give a better failure message, naming the offending type: Spms.Api.Cases.C07_GenericArgument (Has dependency on: Spms.Infrastructure.Options.SmtpOptions).

Why each miss happens

const and nameof (C04, C05). Both are compile-time constants. MailDefaults.FromAddress compiles to ldstr "noreply@spms.local" and nameof(SmtpMailSender) to ldstr "SmtpMailSender". There is no type token left in the method body, which is also why the compiler drops the assembly reference in the console example above.

typeof in attribute arguments (C06, C14). This is the one that bites ASP.NET Core projects, because [ServiceFilter(typeof(...))] and [TypeFilter(typeof(...))] are exactly how controllers pull in filters from an ActionFilter namespace. The attribute blob stores the type as a serialized name, Cecil exposes it as a CustomAttributeArgument, and NetArchTest only looks at the attribute’s own type (ServiceFilterAttribute, which lives in Microsoft.AspNetCore.Mvc). A controller that does nothing but declare that attribute has no dependency on your filter as far as NetArchTest is concerned.

Pass-through return values (C11). C11 calls InfrastructureRegistration.CreateMailer() and returns the result as object. The IL is a call whose declaring type is in the allowed Configuration namespace. IMailSender appears only in the signature of the method being called, which NetArchTest does not inspect. As soon as the code calls a member on the result (C10) or stores it in a typed local, the dependency shows up. Arguably C11 is not a direct dependency anyway, since the API never names the type.

Unused using directives (C01). They are not compiled into anything. If unused usings bother you, that is a job for IDE0005, not an architecture test.

So for the asker’s “does not behave as I expected” case, the most likely explanation is one of these: an API controller with [ServiceFilter(typeof(SomeFilter))] from Spms.Infrastructure.ActionFilter, a constant read from Spms.Infrastructure.Options, or a type that only flows through Spms.Infrastructure.Configuration. NetArchTest is passing those, not failing them.

A rule that holds up: NetArchTest for IL, BannedApiAnalyzers for source

The NetArchTest test for the negative rule is the one from the question, with a useful failure message:

// .NET 11, C# 15, xunit.v3 4.0.4, NetArchTest.Rules 1.3.2
using System.Reflection;
using NetArchTest.Rules;
using Xunit;

public class ApiArchitectureTests
{
    private static readonly Assembly ApiAssembly = typeof(Program).Assembly;

    private static readonly string[] ForbiddenInfrastructureNamespaces =
    [
        "Spms.Infrastructure.ActionFilter",
        "Spms.Infrastructure.DocumentGeneration",
        "Spms.Infrastructure.FileSystem",
        "Spms.Infrastructure.Mail",
        "Spms.Infrastructure.Options",
    ];

    [Fact]
    public void Api_only_uses_the_Infrastructure_Configuration_namespace()
    {
        var result = Types.InAssembly(ApiAssembly)
            .Should()
            .NotHaveDependencyOnAny(ForbiddenInfrastructureNamespaces)
            .GetResult();

        Assert.True(result.IsSuccessful,
            "API types depending on Infrastructure internals:" + Environment.NewLine +
            string.Join(Environment.NewLine, result.FailingTypeNames ?? []));
    }
}

Against the 15-case project this fails and lists C02, C03, C07, C08, C09, C10 and C13. Against an Spms.Api that contains only the Program.cs calling AddInfrastructure(), the test passes. Both runs used the xUnit v3 in-process runner on .NET 11.0.0 (dotnet run on the test project, since xunit.v3 4.0.4 test projects are executables). If you are still on xUnit v2, the test body is identical; the xUnit v3 migration notes cover the project-file changes.

To close the attribute and const holes, add the banned API analyzer to the API project. It works on the Roslyn semantic model during compilation, so it sees things that never reach IL:

<!-- Spms.Api.csproj, .NET 11 -->
<ItemGroup>
  <PackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="5.6.0" PrivateAssets="all" />
  <AdditionalFiles Include="BannedSymbols.txt" />
</ItemGroup>
N:Spms.Infrastructure.ActionFilter;Register filters in Spms.Infrastructure.Configuration instead
N:Spms.Infrastructure.Mail;Use the mail abstraction from Spms.Application
N:Spms.Infrastructure.Options;Options are bound inside AddInfrastructure()
N:Spms.Infrastructure.FileSystem;Not for direct use from the API
N:Spms.Infrastructure.DocumentGeneration;Not for direct use from the API

The N: prefix bans a whole namespace; the format is documented in BannedApiAnalyzers.Help.md. The build output for C06 looks like this:

Cases.cs(28,16): warning RS0030: The symbol 'Spms.Infrastructure.ActionFilter' is banned in this project: Register filters in Spms.Infrastructure.Configuration instead

RS0030 is a warning by default. To make it break the build, set dotnet_diagnostic.RS0030.severity = error in .editorconfig or add <WarningsAsErrors>RS0030</WarningsAsErrors> to the project. Note the table above: the analyzer flags uses (object creation, calls, member access, typeof, attributes, constants) but in this run it did not flag a type that only appears in a declaration or a cast: the constructor parameter in C02, the local variable type in C03, and the (IMailSender) cast in C09 produced no RS0030 of their own. That is exactly the area where NetArchTest is strongest, which is why the two together cover every case in the table except nameof, an unused using, and the pass-through in C11, none of which create a real compile-time coupling to the forbidden code.

Gotchas worth knowing before you rely on these rules

  • NetArchTest.Rules 1.3.2 is from May 2021 and the original repository has not had a commit since July 2023. It still loads .NET 11 assemblies fine (it uses Mono.Cecil 0.11.3), but bug fixes and new features land in NetArchTest.eNhancedEdition (1.4.5, June 2025). The fork keeps the NetArchTest.Rules namespace but renames a few members (FailingTypes, ResideInNamespace, HaveDependencyOnAny in place of HaveDependencyOn), so switching is a small edit, not a pure package swap.
  • eNhancedEdition compares strings case-insensitively by default (Options.Comparer is InvariantCultureIgnoreCase), and it has an opt-in SerachForDependencyInFieldConstant option (that is the actual spelling) for string constants that contain type names. Neither helps with typeof in attribute arguments.
  • Types.InAssembly includes Program from top-level statements, and closures and state machines are folded into their parent type. So when a lambda in a top-level minimal API endpoint violates a rule, expect the failing type to be reported as Program, not as anything named after the endpoint.
  • Dependencies are per namespace, not per assembly. If two assemblies share a namespace, or one assembly contains several root namespaces, write the rule in terms of namespaces and it will do what you expect. Do not pass Assembly.GetName().Name and hope.
  • Internal types do not need a test. If the forbidden namespaces should never be used from outside Infrastructure, making those types internal (with InternalsVisibleTo for Infrastructure’s own tests) gets you a compiler error for free. Architecture tests earn their keep for types that must stay public because DI registration or another layer needs them.

Sources

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.