Bennewitz.Ninja.AssemblyQuality
2026.4.1126
Prefix Reserved
dotnet add package Bennewitz.Ninja.AssemblyQuality --version 2026.4.1126
NuGet\Install-Package Bennewitz.Ninja.AssemblyQuality -Version 2026.4.1126
<PackageReference Include="Bennewitz.Ninja.AssemblyQuality" Version="2026.4.1126" />
<PackageVersion Include="Bennewitz.Ninja.AssemblyQuality" Version="2026.4.1126" />
<PackageReference Include="Bennewitz.Ninja.AssemblyQuality" />
paket add Bennewitz.Ninja.AssemblyQuality --version 2026.4.1126
#r "nuget: Bennewitz.Ninja.AssemblyQuality, 2026.4.1126"
#:package Bennewitz.Ninja.AssemblyQuality@2026.4.1126
#addin nuget:?package=Bennewitz.Ninja.AssemblyQuality&version=2026.4.1126
#tool nuget:?package=Bennewitz.Ninja.AssemblyQuality&version=2026.4.1126
Bennewitz.Ninja.AssemblyQuality
Static analysis rules for the shape a .NET assembly ships — read by reflection over the compiled output, which is the thing a consumer actually binds against. A source analyser sees what was written; this sees what was published.
The assembly-shaped companion to Bennewitz.Ninja.XamlQuality: that one reads markup, this one reads types. Every rule here came from a guard written inline in a real repository, where it could assert "no offenders today" and never that it would find one.
Install
dotnet add package Bennewitz.Ninja.AssemblyQuality
Run it where it belongs: in a test project, against the untrimmed build. The rules read by
reflection, so they are not trim-safe. IAssemblyRule.Analyze carries
[RequiresUnreferencedCode], so calling it from an application with trimming or AOT enabled
raises a warning at the call site. Without that warning, a trimmed scan would complete and quietly
report less than it should.
Trusting a clean result
On its own, a rule with no findings says less than it seems to. Together, these three checks make it mean something:
| Check | What it rules out |
|---|---|
Inspected > 0 |
The rule had nothing it could check, not "checked and clean". |
Skipped is empty |
The rule examined only what it could load, not everything. |
| A check that fails on the wrong assembly | The rules ran against whatever they were handed, not the assembly you meant. |
Skipped applies to the rules that load types or references: BNAQ1001, BNAQ1002, BNAQ1004
and BNAQ1006. BNAQ1003 reads only the names in the reference list and BNAQ1005 only the assembly's
own grants; they load nothing, and so never skip. An empty-Skipped assertion on either passes, but
it cannot fail.
Assert on Skipped with the entries in the message, for example
Assert.True(result.Skipped.Count == 0, string.Join("\n", result.Skipped)). xunit's
Assert.Empty shortens each string it prints, which cuts off the part of an entry that says what
would not load and why.
The first two checks in the table describe the scan, and both pass when the scan is pointed at the wrong assembly. Before running the rules, pin the subject by asserting something that is true only of it, such as a dependency only it references, or one its neighbours carry and it must not. A helper that loads an assembly by name and then checks that the name matches does not do this: it passes for whatever it loaded.
Licence
MIT. See LICENSE.
Rules
| Id | Requires |
|---|---|
BNAQ1001 |
No public method takes a CancellationToken with a default value. |
BNAQ1002 |
No type from a leak-prone namespace appears in the public surface. |
BNAQ1003 |
An assembly references none of the assemblies its layer forbids. |
BNAQ1004 |
No declared namespace segment shadows the root namespace of a referenced assembly. |
BNAQ1005 |
Every InternalsVisibleTo grant names an assembly the caller allows. |
BNAQ1006 |
Every reference into another assembly resolves, and every one into an internal is still granted. |
BNAQ1010 |
A named type or member is used only where its confinement allows it. |
BNAQ1011 |
Every key a marked parameter is given is one of its key class's constants, and every such constant is given to one. |
Renamed after 2026.3.922. Up to and including that version the IDs were AQ1001–AQ1004.
The numbers are unchanged, so AQ1004 is now BNAQ1004: rename any suppression or filter that
names an old ID, or it stops matching. The prefix is BN plus the product's initials, shared across
the Bennewitz.Ninja quality packages, and it will not change again.
The table above is rendered from the rule types — Id and Summary on each IAssemblyRule — and
a test fails if it drifts. Regenerate it with AQ_UPDATE_DOCS=1 dotnet test --solution Inspections.slnx
and commit the result.
Every rule reports; none of them assert. A finding can fail a build, warn in CI or print in a report — the severity is the consumer's to choose, and a library that threw would have chosen both the runner and the severity for them.
Assert on Inspected, not only on Findings. A rule given no assemblies, or one configured to
forbid nothing, returns zero findings and reads exactly like a clean result. Inspected is what
tells "nothing is wrong" apart from "nothing was checked" — which is the failure every guard this
library replaced actually had.
Source-side counterparts. Three of these rules also exist as Roslyn analyzers in
Bennewitz.Ninja.CodeQuality, with the same
number under the BNCQ prefix. The analyzer reports at the line as it is typed and reads the source,
internal code included. This package reads what actually shipped, including everything a source
generator added. Where you can, run both: each sees something the other cannot.
BNAQ1001
No public method takes a CancellationToken with a default value, and no public method is a
token-less overload of a sibling that takes one. A policy rule rather than a defect rule, so adopt it
deliberately. Counterpart: BNCQ1001,
off by default, which also reads protected methods and constructors.
BNAQ1002
No type from a leak-prone namespace appears in a public signature, generic arguments unwrapped.
new SurfaceLeakRule(extra) adds namespaces to LeakProneNamespaces; SurfaceLeakRule.Only(list)
replaces them. Counterpart: BNCQ1002,
which walks referenced types transitively and also reads generic constraints and a containing type's
type arguments, such as List<JsonNode>.Enumerator. This rule reads signature types only.
BNAQ1003
No assembly directly references one its layer forbids, matched by simple-name prefix. It forbids
nothing until configured, and then says so with Inspected of zero. There is no source-side
counterpart: Microsoft.CodeAnalysis.BannedApiAnalyzers already reports a forbidden use at its call
site, while this rule reads the reference list the compiled assembly actually kept.
BNAQ1004
No namespace segment after the first shadows the root namespace of a referenced assembly.
NamespaceShadowRule.IncludingInternalTypes() extends it from public types to all of them.
Counterpart: BNCQ1004.
⚠ A reference that does not load at run time is invisible here and visible there. This rule
compares against the roots of references it can load, and names any it cannot in Skipped. The
analyzer runs where the compiler has every reference. Measured on this repository's own fixtures:
BNCQ1004 reports the Orphan.Absent shadow in tests/fixtures/Orphan, whose referenced assembly
is deliberately missing at run time, while BNAQ1004 lists that reference in Skipped.
BNAQ1005
Every InternalsVisibleTo grant names an assembly the caller allows. Pass the allowed names:
new FriendGrantRule(allowed). Unconfigured, it reports Inspected of zero, as BNAQ1003 does.
There is no source-side counterpart: what matters is the grant list the compiled assembly carries,
whichever of the attribute, the SDK's <InternalsVisibleTo> item or an <AssemblyAttribute> put it
there.
⛔ A wrong grant fails silently. A grant matches an assembly's simple name only, so one naming a
namespace (Bennewitz.Ninja.X where the assembly is X) or a misspelled assembly compiles, ships
and grants nothing. Names compare case-insensitively, and a PublicKey= part is ignored.
Outside the Bennewitz.Ninja family it answers the same question for any solution that grants internals: pass the assemblies your solution builds, plus any you grant to on purpose. Scan your shipped assemblies and allow your test assemblies by name, since a scan that leaves the tests out cannot tell they exist.
BNAQ1006
Every reference into another assembly resolves, and every one into an internal is still granted. It
examines references into assemblies outside the scan and outside the shared framework, resolves each
through the runtime's own Module.ResolveType / ResolveMember, and reports:
- a type or member the loaded version no longer has, which fails at run time with
TypeLoadExceptionorMissingMethodException. A removed type is reported once, not once per member reference through it; - a reference to an internal whose provider no longer grants the scanned assembly, which resolves
fine and then fails at the call with
MethodAccessException.
A reference that will not load is named in Skipped, and so is an assembly with no file behind it.
There is no source-side counterpart: the question is about the version that loads, which does not
exist at compile time.
⭐ Run it at the provider's release, against the consumers already published. A consumer's own tests compile against the provider they load, so a removed internal is a compile error there first, and this rule could almost never fail. The break happens in an application that resolves a newer provider under a consumer built against an older one, and the provider's release is the one place that pairing can be assembled before it ships. In the provider's test project:
<ItemGroup>
<ProjectReference Include="..\..\src\Provider\Provider.csproj" />
<PackageDownload Include="Some.Consumer" Version="[1.2.3]" />
</ItemGroup>
<Target Name="CopyConsumers" AfterTargets="Build">
<PropertyGroup>
<_ConsumerLib>$([System.IO.Path]::Combine($(NuGetPackageRoot), 'some.consumer', '1.2.3', 'lib', 'net10.0'))</_ConsumerLib>
</PropertyGroup>
<ItemGroup>
<_Consumer Include="$(_ConsumerLib)/*.dll" />
</ItemGroup>
<Copy SourceFiles="@(_Consumer)" DestinationFolder="$(OutDir)consumers" />
</Target>
Then load each consumer in an AssemblyLoadContext of its own that resolves the provider from the
test's output, which is the source build, and scan the consumer. Keep the context alive until the
scan has finished: a collectible one nothing holds unloads itself at the next garbage collection, and
the rule then throws InvalidOperationException rather than report a scan that examined nothing. A
context that is not collectible, as here, lives as long as the test process:
AssemblyLoadContext context = new("consumer");
context.Resolving += (_, name) =>
{
string candidate = Path.Combine(AppContext.BaseDirectory, name.Name + ".dll");
return File.Exists(candidate) ? context.LoadFromAssemblyPath(candidate) : null;
};
Assembly consumer = context.LoadFromAssemblyPath(Path.Combine(AppContext.BaseDirectory, "consumers", "Some.Consumer.dll"));
AssemblyRuleResult result = new FriendReferenceRule().Analyze(AssemblyScanContext.Of(consumer));
Assert.True(result.Findings.Count == 0, string.Join("\n", result.Findings));
Assert.True(result.Inspected > 0, "the consumer must reference the provider at all");
Outside the Bennewitz.Ninja family it answers the same question for any library with published dependents, internals or not: will what they call still be there when an application pairs them with this release?
BNAQ1010
A named type or member is used only where its confinement allows it. It reads every method body, the compiler's lambdas, local functions, async and iterator state machines, static constructors, accessors and compiled XAML among them, as ICSharpCode.Decompiler's transformed ILAst, and credits a use in generated code to the method the source wrote. Each confinement names a type or a member by its full name, in reflection syntax, which reaches an internal type of a library the consumer cannot reference:
var rule = new ConfinedUseRule(
[
// No window is constructed but the ones the assembly declares.
ConfinedUse.Constructing("Avalonia.Controls.Window") with
{
IncludingSubtypes = true,
ExceptTypesTheScanDeclares = true,
},
// Colours and brushes are made in one type and the types nested in it.
ConfinedUse.AnyMemberOf("Avalonia.Media.Colors") with { AllowedInTypes = ["MyApp.Palette"] },
ConfinedUse.Member("Avalonia.Media.Color", "Parse") with { AllowedInTypes = ["MyApp.Palette"] },
// Resources are looked up by one helper, and by the markup that says so.
ConfinedUse.Member("Avalonia.Controls.IResourceNode", "TryGetResource") with
{
IncludingSubtypes = true,
AllowedInMethods = ["MyApp.Palette::Brush"],
AllowedInMarkup = ["Theme.axaml"],
},
]);
What counts as a use is the confinement's: constructing the type (
newobj, a constructor called on an address,initobjof a value type), any use of its members (a call, a delegate made from a method, a read of a field or a property), or one member by name. A constructor chaining to its own base or its own type's constructs nothing: it is listed in the reading as aChainand never reported.IncludingSubtypesmatches the types that derive from the named one or implement it, directly or through another interface, and a member by its name and parameters on any of them. A call holds the member the compiler bound to, soTryGetResourcenamed onIResourceNodereaches a call throughApplication, which declares its own.ExceptTypesTheScanDeclaresleaves out a type an assembly of the scan declares, as a window class the assembly writes is.A place is allowed by type, its nested types included; by method, written
Type::Method, its lambdas and state machine included; or by markup file, by the file name the symbols give the code compiled from it.KeyParameterallows a call or a construction by its key: the index, among the member's parameters, of the argument that is its key,0forTryGetResource's and1for theFindResourceextension's, whose first is the control it extends. The use is allowed wherever every value that argument takes traces, asBNAQ1011follows a key, to a parameter marked[ResourceKey], directly or through private methods. A literal, a field, a computed key, or a parameter the attribute does not mark is allowed only by a place, inside a marked method or not:// A resource is looked up only by a key a marked helper was given. ConfinedUse.Member("Avalonia.Controls.IResourceNode", "TryGetResource") with { IncludingSubtypes = true, KeyParameter = 0, },
ConfinedUseRule.Read returns every matched use, allowed or not, with its kind, the method that makes it, its
file and line, its IL offset and, under KeyParameter, each value its key takes, and Analyze reports the ones
not allowed. A finding carries Source, the file
and line, wherever the assembly's portable PDB, embedded or beside it, gives one.
⚠ Assert your positive controls through the reading. Inspected counts the method bodies read, which a
matcher that had stopped matching would still read, so "no findings, Inspected above zero, nothing skipped" is
not enough on its own. Assert that the reading lists the allowed uses you know are there: the chain each window
class makes, the parse your palette calls.
Skipped names an assembly with no file to read, a configured name that resolves to nothing in the scan or what
it references (once, however many assemblies are scanned), a type whose ancestry a match depended on and could
not follow, a generated name the reader cannot take apart, and a method body the decompiler cannot read. There is
no source-side counterpart: where a thing is used across an assembly, compiled markup included, is what shipped.
This rule makes the package depend on ICSharpCode.Decompiler (MIT), its first dependency, which brings System.Collections.Immutable and System.Reflection.Metadata with it, both part of .NET 10.
BNAQ1011
Every key a marked parameter is given is one of its key class's constants, and every such constant is given to
one. A helper marks its key parameter with the class whose const string fields are its keys, so the code says
which methods are helpers, which argument is the key and where the keys live, and a rename keeps it true:
internal static class DialogColors
{
internal const string Accent = "Dialog.Accent";
internal const string Warning = "Dialog.Warning";
internal static IBrush Brush([ResourceKey(typeof(DialogColors))] string key) => ...;
}
No package ships the attribute, since the code that carries it is shipped code, which a test package cannot reach.
Declare it once, internal, in the lowest project that needs it; its friend grants make it visible to the rest, and
the rule finds it by its full name:
namespace Bennewitz.Ninja;
/// <summary>Marks a parameter whose argument must be one of <see cref="Keys"/>' const string fields.</summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class ResourceKeyAttribute(Type keys) : Attribute
{
public Type Keys { get; } = keys;
}
⛔ Declare it once. Two projects that each declare it, one referencing the other, get CS0436, an error under warnings as errors.
- A key is followed within its method through locals, ternaries,
??and tuples, and through a parameter to every caller in the scan, to a depth of eight. The key class may be nested, or in an assembly the scanned one references. - What cannot be followed is a finding: a field, a call's result, a delegate's result, a lambda's parameter, and the parameter of a method whose callers the scan cannot all see, one visible outside its assembly, one that overrides or implements another, and one made into a delegate. A marked helper made into a delegate is reported too, since no call shows its keys, and so is a marked parameter handed one that names another class.
- ⛔ A literal equal to a key is that key. A
constis compiled into each of its uses, so the rule reads a key by its value, and"Dialog.Accent"cannot be told fromDialogColors.Accent. - Every field must reach a marked parameter naming its class somewhere in the scan, and every marked parameter naming one class shares its keys. A class named only by a helper outside the scan is checked for the keys the scan gives it, not for the fields it never gives.
HelperKeyRule.Read returns every marked parameter the scan declares, every call to a marked parameter, with each
value its key takes and where that value arises, and every delegate made of a method with one; Analyze reports
from it. Inspected is the number of calls to marked parameters, zero where none is called, which is what a
misspelt attribute leaves. Skipped names an assembly with no file to read, a method body the decompiler cannot
read, a marked parameter that takes no string, an attribute without one type, given to its constructor, that
resolves, a key class with no const string field, and two fields of one class that hold one value. It has no
source-side counterpart yet.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- ICSharpCode.Decompiler (>= 11.2.0.10050)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 2026.4.1126 | 344 | 11/26/2026 |
| 2026.4.1031 | 2,145 | 10/31/2026 |
| 2026.4.1029 | 361 | 10/29/2026 |
| 2026.3.929 | 406 | 9/29/2026 |
| 2026.3.928 | 2,209 | 9/28/2026 |
| 2026.3.925 | 284 | 9/25/2026 |
| 2026.3.922 | 796 | 9/22/2026 |