Bennewitz.Ninja.CodeQuality
2026.4.1203
Prefix Reserved
dotnet add package Bennewitz.Ninja.CodeQuality --version 2026.4.1203
NuGet\Install-Package Bennewitz.Ninja.CodeQuality -Version 2026.4.1203
<PackageReference Include="Bennewitz.Ninja.CodeQuality" Version="2026.4.1203"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="Bennewitz.Ninja.CodeQuality" Version="2026.4.1203" />
<PackageReference Include="Bennewitz.Ninja.CodeQuality"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add Bennewitz.Ninja.CodeQuality --version 2026.4.1203
#r "nuget: Bennewitz.Ninja.CodeQuality, 2026.4.1203"
#:package Bennewitz.Ninja.CodeQuality@2026.4.1203
#addin nuget:?package=Bennewitz.Ninja.CodeQuality&version=2026.4.1203
#tool nuget:?package=Bennewitz.Ninja.CodeQuality&version=2026.4.1203
Bennewitz.Ninja.CodeQuality
Roslyn analyzers for the shape of a .NET library's source: a namespace segment that shadows a
referenced root namespace, an implementation type leaking into the public surface, a cancellation
token a caller can leave out, and the System.Reactive calls, callbacks and gates where one exception
ends the process, vanishes or leaves a feature shut. Three rules are the compile-time counterparts of
Bennewitz.Ninja.AssemblyQuality
rules that read the shipped assembly, and carry their numbers: BNCQ1004 finds while you type what
BNAQ1004 finds after the build. A rule with no counterpart takes the next free number, and a rule
about Avalonia the next from BNCQ3001, so the rules about a framework you may not use stand apart.
A rule's section names its counterpart, if it has one.
Install
dotnet add package Bennewitz.Ninja.CodeQuality
A development dependency: the analyzer runs inside the compiler, ships nothing at run time, and is
not passed on to whoever references your package. It needs a compiler from Roslyn 4.14 on, which is
Visual Studio 2022 17.14 or a .NET 9.0.3xx SDK or later. An older compiler, such as the .NET 8
SDK's, reports CS9057 and skips the analyzer: every rule goes quiet, and the build fails only
where warnings are errors.
Rules
| Id | Default | Reports |
|---|---|---|
BNCQ1001 |
off | A visible method lets the caller leave the cancellation token out |
BNCQ1002 |
on | A type from a leak-prone namespace appears in the visible surface |
BNCQ1004 |
on | A namespace segment shadows the root namespace of a referenced assembly |
BNCQ1005 |
on | A System.Reactive time operator is given no scheduler |
BNCQ1006 |
on | An async delegate is given to a System.Reactive operator that does not await it |
BNCQ1007 |
on | A producer built by Observable.Create catches what OnNext throws |
BNCQ1008 |
on | A gate taken in a body is released outside a finally clause |
BNCQ1009 |
on | A callback no caller catches is not wholly inside a try/catch |
BNCQ1011 |
on | A key given to a marked parameter is not one of its key class's constants |
BNCQ1012 |
on | A log template is not in the family's one form |
BNCQ3001 |
on | An Avalonia DispatcherTimer's Tick handler is not wholly inside a try/catch |
BNCQ3002 |
on | A wait blocks on the task a headless dispatch returns |
BNCQ3003 |
on | An Avalonia resource lookup's key does not come from a marked parameter |
BNCQ3004 |
on | A headless test assembly does not state its isolation, or states PerAssembly with no warm-up |
BNCQ3005 |
on | Whether an application exists decides whether work runs on the UI thread |
BNCQ3006 |
on | A converter reads the application's theme |
The table is rendered from the analyzers' own descriptors, and a test fails if it drifts.
BNCQ1003 is reserved: its counterpart
BNAQ1003 forbids a
reference, and a forbidden use site at compile time is already
Microsoft.CodeAnalysis.BannedApiAnalyzers'
job.
Where a rule comes from is shown by its help link (its section below), its category
(Bennewitz.Ninja.CodeQuality) and the package id, not by a longer ID. BNCQ is BN plus the
product's initials, the scheme across the Bennewitz.Ninja quality packages, and it will not change.
Every rule decides once per compilation whether it applies, and registers nothing where it does not: a project the rule has nothing to compare against pays a few lookups at compilation start and nothing per file. A build with no findings cannot tell that from "checked and clean", which is why each rule's tests show it firing on a real violation as well as staying silent.
BNCQ1001
A visible method lets the caller leave the cancellation token out. Off by default. Counterpart:
BNAQ1001.
A CancellationToken parameter with a default value hands every caller who forgets it
CancellationToken.None: an operation that cannot be cancelled, chosen by nobody, visible nowhere.
The call compiles, runs, and hangs on shutdown. An overload that leaves the token out while a
same-named sibling takes it is the same default, moved one overload over, and is reported too:
when its parameters are the sibling's with the token removed, or a leading run of them.
The fix that holds is to require the token ahead of any optional parameter, so that a caller
who means CancellationToken.None has to write it. Dropping the token's default alone is CS1737
when an optional parameter follows it.
This is a policy, not a defect: the BCL defaults its own tokens everywhere, and a finding is not
evidence of a bug. It is the rule a library adopts when its cancellation contract is load-bearing.
Turn it on in .editorconfig:
[*.cs]
dotnet_diagnostic.BNCQ1001.severity = warning
Visible means public or protected at every level, so a protected method counts, and so does a
constructor; BNAQ1001 reads neither. Compiler-generated members, accessors, operators and
explicit interface implementations are skipped: a caller cannot pass them a token by name. Inert in
a compilation that cannot name CancellationToken.
BNCQ1002
A type from a leak-prone namespace appears in the visible surface. Counterpart:
BNAQ1002.
Return a JsonNode from one public method and every consumer now binds against
System.Text.Json, its version, its behaviour and its breaking changes, whether or not they
serialize anything. Swapping the serializer later is then a breaking change to an API that was
never about serialization. The rule reads every visible member's signature, what a type derives
from and implements, and generic constraints. It unwraps generic arguments, including a containing
type's, and array elements, so a Task<JsonNode>, a List<JsonNode>.Enumerator and a
where T : JsonNode leak exactly as much as a bare JsonNode.
Unlike BNAQ1002, the walk is transitive through referenced types: a public Envelope from
another package whose Payload is a JObject binds the consumer to Newtonsoft one hop further,
and the message names the hop. A covered type the signature names itself is reported before any
longer path. Your own types are not opened, because their members are reported where they are
declared. A referenced type is opened only if its assembly can reach a covered namespace, directly
or through its own references, which keeps the walk off Task<T>, List<T> and most of the
framework.
A C# 14 extension(...) block exposes its receiver: calling node.Touch() binds the consumer to
JsonNode as surely as a classic this JsonNode parameter does. So a covered receiver, or a
covered constraint on a generic block, is reported at the block, and the members inside are checked
like any other.
The default namespaces are the ones that leak in practice: System.Text.Json.Nodes and
Newtonsoft.Json.Linq. The type most likely to leak from your library is one no general list
will name, so .editorconfig replaces the list with yours, comma or semicolon separated. A
prefix covers the namespace and everything beneath it on a segment boundary.
[*.cs]
bennewitz_ninja_codequality.BNCQ1002.namespaces = System.Text.Json.Nodes, Newtonsoft.Json.Linq, Acme.Internal
The list is read once per compilation, from a global config first and then from the first source
file whose options carry it, so it belongs in the repository's root .editorconfig. An empty list
forbids nothing. Inert where no covered namespace is in reach. A library whose surface is JSON on
purpose, such as a JSON editor, exposes these types by design: set the list to the namespaces it
does not mean to expose, or empty it.
BNCQ1004
A namespace segment shadows the root namespace of a referenced assembly. Counterpart:
BNAQ1004.
C# resolves the first identifier of a qualified name by walking outward from the current
namespace. Inside Acme.Widgets.Avalonia, the name Avalonia finds your namespace first, and
Avalonia.Media.Color fails to compile looking for Acme.Widgets.Avalonia.Media.Color: CS0234,
reported at the use site, about a type that plainly exists, possibly years after the namespace was
declared. The rule reports the segment itself, in every declaration that carries it.
Only segments after the first can shadow. A namespace's own root is the tree it already lives in,
so Acme.Widgets beside a referenced Acme.Other resolves perfectly. A root is a top-level
namespace a referenced assembly declares a type you can see in; a namespace holding only internal
types counts only where that assembly makes its internals visible to yours, and a reference behind
an extern alias counts only when one of its aliases is global.
Two fixes, not one. Where namespaces follow the assembly name, renaming only the namespace breaks
that convention, so the fix there renames assembly and namespace together, .Avalonia to
.AvaloniaUI. The package id takes no part in name resolution and may keep the word. Inert in a
compilation whose references declare no visible namespace.
BNCQ1005
A System.Reactive time operator is given no scheduler. No counterpart.
Throttle, Sample, Interval, Timer, Delay, Buffer and Window by time, and Timeout,
deliver on Rx's default scheduler when they are given none. A throw there has no caller to go back
to, so it ends the process, and an onError does not stop that. Timeout with no onError ends it
with no code of yours throwing at all. The rule reports the call, at the operator's name, when its
overload takes a TimeSpan or a DateTimeOffset and no IScheduler. What was measured is in
the time operator's entry
of docs/exception-resilience.md.
The fix is to pass a scheduler: the UI scheduler for work that touches the view, a pool scheduler otherwise. Then guard the handler, because a pool scheduler turns the ending into a subscription that dies silently.
Only the operators measured to deliver on the scheduler are named: Replay, Skip and Take by
time are not. A scheduler you chose, Scheduler.Default included, is not reported either. It ends
the process on a throw too, but choosing one is not a defect the rule can see.
The finding is the shape, and whether a throw can follow is decided by what runs downstream. On a
real application's code, three of its five findings had nothing downstream that could throw on real
input, and two ended the process. Where nothing downstream can throw, suppress the finding there,
with the reason. Inert in a compilation that cannot name System.Reactive.Linq.Observable.
BNCQ1006
An async delegate is given to a System.Reactive operator that does not await it. No counterpart.
Subscribe, Do and Finally take an Action, so an async lambda given to one is async void: its
exception is rethrown on the thread it resumed on, and off a UI thread that ends the process. An
async Select makes each value a task nobody awaits, and a failure in one goes unobserved. The rule
reports an async lambda or anonymous method given to a void delegate parameter of System.Reactive's
Observable or ObservableExtensions, at its async keyword, and a Select whose selector returns
Task or Task<T>, at its name. What was measured is in
the async lambda's entry
of docs/exception-resilience.md.
The fix is SelectMany with Observable.FromAsync, which awaits the work and carries its failure to
onError, or a synchronous handler:
source.SelectMany(value => Observable.FromAsync(() => SaveAsync(value)))
.Subscribe(_ => { }, error => log.Error(error));
A Select whose tasks go straight to Concat, Merge or Switch is not reported: those take an
observable of tasks and await each. An async lambda given to any other void delegate is
Microsoft.VisualStudio.Threading.Analyzers' VSTHRD101, and an async void method passed as a method
group is its VSTHRD100, at the method, so neither is reported here. Inert in a compilation that
cannot name System.Reactive.Linq.Observable.
BNCQ1007
A producer built by Observable.Create catches what OnNext throws. No counterpart.
A subscriber's throw comes out of OnNext after Rx has disposed the producer's subscription. A catch
around the call swallows that failure, and the producer carries on for nobody: every subscriber of a
shared source stops, and nothing says why. The rule reports the OnNext of the observer
Observable.Create hands its delegate, followed into the lambdas and local functions written inside
it, when the call sits in a try block whose catch can carry on: its end can be reached, or it
continues a loop. What was measured is in
the producer's entry
of docs/exception-resilience.md.
The fix is to catch only the producer's own work, and call OnNext outside the try:
string text;
try
{
text = File.ReadAllText(path);
}
catch (IOException error)
{
observer.OnError(error);
return Disposable.Empty;
}
observer.OnNext(text);
A catch that rethrows, returns or breaks out is not reported. Neither is a catch around a
Subject's OnNext: there it is a guard, and the subject's other subscribers kept every value. Inert
in a compilation that cannot name System.Reactive.Linq.Observable.
BNCQ1008
A gate taken in a body is released outside a finally clause. No counterpart.
One throw between taking a gate and releasing it leaves the gate taken, and every later caller
waits for good. The rule reports a release outside a finally clause in a body that takes the same
field, local or parameter: SemaphoreSlim (Wait, WaitAsync, Release), Semaphore
(WaitOne, Release), Mutex (WaitOne, ReleaseMutex), Monitor (Enter, TryEnter,
Exit, on the object passed) and ReaderWriterLockSlim (its Enter, TryEnter and Exit
methods). What was measured is in
the semaphore's entry
of docs/exception-resilience.md.
The fix is to release it in the finally of a try that starts once it is taken:
await gate.WaitAsync();
try
{
Save();
}
finally
{
gate.Release();
}
Each lambda, anonymous method and local function is a body of its own, so a gate taken in a method
and released by a continuation it schedules is not reported: the release belongs to the
continuation, and nothing in the method could put it in a finally. Inert in a compilation that can
name none of the five types.
BNCQ1009
A callback no caller catches is not wholly inside a try/catch. No counterpart.
Nothing above these callbacks catches, so a throw in one goes where nobody can handle it:
| Callback | A throw there |
|---|---|
A System.Threading.Timer callback, a Thread's start, a ThreadPool.QueueUserWorkItem callback |
ends the process |
A Process OutputDataReceived, ErrorDataReceived or Exited handler |
ends the process |
| A finalizer | ends the process, at the collection that runs it |
A FileSystemWatcher Created, Changed, Deleted or Renamed handler |
ends the process on Windows, and silences the watcher on Linux |
A System.Timers.Timer Elapsed handler |
is swallowed for good: the timer keeps ticking and nothing reports it |
The rule reports such a body when it is not wholly inside one try statement whose catch takes
Exception, or everything, and does not end in a throw, with no filter, or one that lets only a
fatal exception through. It reads a lambda, an
anonymous method, and a method group naming a method or local function written in the same
compilation; a method from a reference is not opened. A delegate passed through a local is read
as what its declaration gives it, and reported at the local's name, unless the block declaring it
assigns it again, passes it by ref or out, or takes a reference to it. An empty body is not
reported. What was measured is in the timer, thread, watcher, process and finalizer entries of
docs/exception-resilience.md.
The fix is one try/catch that logs, around the whole body:
watcher.Created += (_, e) =>
{
try
{
Load(e.FullPath);
}
catch (Exception error)
{
log.Error(error, "Could not load {Path}", e.FullPath);
}
};
A catch-all that lets a fatal exception through guards the body as well. Use it where a check
reports a catch-all with no filter, as CodeQL's cs/catch-of-all-exceptions does. The filter
tests the caught variable with is not against fatal types alone: OutOfMemoryException,
StackOverflowException and AccessViolationException. It may be written e is not F,
e is not (F or G), e is not F and not G, e is not F && e is not G, !(e is F) or
!(e is F or G):
catch (Exception error) when (error is not OutOfMemoryException)
On .NET 10 neither a stack overflow nor an access violation reaches a catch, so the exception such a
filter lets past is an OutOfMemoryException, which ends the process wherever it surfaces. Any other
filter decides at run time what it lets through, so the body is still reported.
The body is judged as written. A body that only posts to a dispatcher, or calls a method that
catches for itself, is still reported, because the rule cannot see what a call throws; suppress it
there, with the reason. Only the callbacks measured to end the process or swallow the throw are
read. A DispatcherTimer's Tick is Avalonia's, and BNCQ3001's.
So the finding is the shape: on the family's repositories and a real application's code, 12 of its 13 findings could not throw on real input, and the one that could was a probe that throws on purpose. Inert in a compilation that can name none of the six types.
BNCQ1011
A key given to a marked parameter is not one of its key class's constants. Counterpart:
BNAQ1011,
whose section shows the attribute and how to declare it once.
A helper marks its key parameter with Bennewitz.Ninja.ResourceKeyAttribute, naming the class whose const string
fields are its keys, and every value an argument to it can take must be one of them, named, so that renaming a key
changes every use of it:
DialogColors.Brush(DialogColors.Accent); // clean
DialogColors.Brush("Dialog.Accent"); // BNCQ1011: a literal, though it equals the key
A key is followed through locals, conditionals,
??, switch expressions and tuples, and through a parameter to every caller in the compilation, to a depth of eight. A path ends clean at a constant of the key class, or at a parameter marked with the same class, whose own callers are checked where they call.Anything else is reported at the argument, and the message names each value and where it arises: a literal, a constant of another class, a field that is not a constant, a property, a call's result, a computed or interpolated string, an element of an array, a
foreachvariable, a lambda's parameter, and the parameter of a method whose callers the compilation cannot all see, one visible outside the assembly, one that overrides or implements another, one made into a delegate, and one no call in the compilation makes.A marked method made into a delegate is reported where it is made, since no call shows its keys.
⚠ Stricter than
BNAQ1011on a literal. IL cannot tell"Dialog.Accent"fromDialogColors.Accent, since aconstis compiled into each use; source can, and only the named constant follows a rename.A table of keys is not followed. A key read out of an array is reported, as
BNAQ1011reports it in IL. Call the helper once per key instead, each line pairing its key with whatever goes with it:Paint(Tokens.Added, DialogColors.Brush(DialogColors.Added)); Paint(Tokens.Removed, DialogColors.Brush(DialogColors.Removed));
Whether every constant of the key class is passed somewhere stays with BNAQ1011, which reads every project's
calls; a compilation sees its own. A mark whose class the compiler cannot read is not checked. A file a tool wrote,
by its name or its <auto-generated> header, is read for the calls it makes and never reported. Inert in a
compilation that cannot name the attribute, declared in it or in an assembly it references.
BNCQ1012
A log template is not in the family's one form. No counterpart: a template exists only in source.
Every log line the family writes takes one form, so one search finds every line of a kind and every value by its key:
[Backup.Tab] index={Index} tab="{Tab}" elapsedMs={ElapsedMs}
- A tag first:
[Area.Kind], each part an upper-case letter and then letters or digits, one dot, nothing before it.[Area]alone is not the form. - Then key=value pairs only: one space before each, a camelCase key,
=and a value, and nothing after the last pair. A value is quoted,tab="{Tab}", or a run with no space and no quote,elapsedMs={Ms}; free text is quoted. {{and}}are literal braces.
The rule reads the template of these calls, by its template parameter, so an overload added later is read too:
- Microsoft.Extensions.Logging's
LogTracetoLogCriticalandLog. LoggerMessage.Definein every arity, and theMessageof[LoggerMessage].- Serilog's
VerbosetoFatalandWrite, onSerilog.Log, onSerilog.ILoggerand on every type that implements it.
It reports the first place a template leaves the form, and what is there. It also reports:
- A template that is not a constant, a literal, a
constor a concatenation of them, since its form cannot be read, and an interpolated template gives a structured sink no holes to keep. - A hole whose format is
l. The family's{Message:lj}sinks already apply it to every string, and on an enum it throws or drops the line. - An enum, or a nullable one, given to a hole. Those sinks print it quoted,
level="Warning", where every other identifier is bare, so pass its name,mode.ToString().
How a hole is matched to its argument:
- by position, or by number where every hole is numbered;
- by parameter name, ignoring case, for
[LoggerMessage]; - by type argument for
Define.
Where holes and arguments do not pair, the compiler's own analyzers say so, and no enum is placed.
Whether a line is one per user action, what a value may hold, and whether a bare hole holds free text are review's.
BeginScope writes no line, and is not read.
No template is exempt by its shape. A line that passes on one already written is suppressed where it is, with its reason, as a sink that writes an already rendered line does:
#pragma warning disable BNCQ1012 // Writes a line already rendered in the form.
inner.Write(level, "{RawLine}", line);
#pragma warning restore BNCQ1012
Text forwarded from elsewhere that is not yet a line is a quoted value of a line in the form, as
line="{EventLine}" after the line's own tag.
A file a tool wrote, by its name or its <auto-generated> header, is not read. A [GeneratedCode] attribute
decides nothing: Roslyn takes a partial method for generated code where its other half carries one, so the attribute
would hide a consumer's own [LoggerMessage] method and the body of an MVVM Toolkit On…Changed hook.
Inert in a compilation that names neither Microsoft.Extensions.Logging.ILogger nor Serilog.ILogger.
BNCQ3001
An Avalonia DispatcherTimer's Tick handler is not wholly inside a try/catch. No counterpart.
One throw from a Tick handler stops the timer for good. IsEnabled still reads true,
Dispatcher.UnhandledException never hears of it, and the exception surfaces only as an unobserved
task's, at some later garbage collection. The rule reports a handler given by Tick += or to the
constructor that takes one, judged as BNCQ1009 judges a body. DispatcherTimer.Run
and RunOnce were not measured, and are not read. What was measured is in
the DispatcherTimer entry
of docs/avalonia-gotchas.md.
The fix is one try/catch that logs, around the whole body, its catch-all unfiltered or letting only a
fatal exception through, as BNCQ1009 says. On the family's repositories and a real
application's code the rule reported one handler, which could not throw on real input; suppress such
a finding there, with the reason. The rules about Avalonia are numbered from BNCQ3001, so they stand apart from the rest. Inert in a
compilation that cannot name Avalonia.Threading.DispatcherTimer.
BNCQ3002
A wait blocks on the task a headless dispatch returns. No counterpart.
Avalonia's HeadlessUnitTestSession completes the task Dispatch returns on its one consumer thread, so the
rest of a test that awaited a dispatch, and xUnit's start of the next test, can run on that thread. A wait
there for another dispatch waits on the only thread that could run it, and the test run never ends;
Microsoft.Testing.Platform's --timeout does not end it either. Whether it happens depends on the order the
tests run in, so a suite can pass locally and hang in CI. Measured on Avalonia 12.1.3, where every wait the
rule reads hung after an awaited dispatch; the source is unchanged at 12.1.6. What was measured is in
the entry on blocking on Dispatch
of docs/avalonia-gotchas.md.
The rule reports the task's Wait, in any overload, its Result, GetAwaiter().GetResult(), through
ConfigureAwait too, and Task.WaitAll or Task.WaitAny given the task, where the task is a call to any
Dispatch overload or a local that holds one. It reports a wait wherever it is, in a helper or inside a
dispatched action, which blocks the session's thread on itself every time. A task held in a field, a
parameter or a return value is not followed.
The fix is to await the dispatch, or return its task, and make the test async Task. A wait inside a
delegate that Task.Run runs, before any await in it, never runs on the session's thread, and neither
does a Result read after the task was awaited: suppress such a finding where it is, with the reason, or
take the value from the await. Inert in a compilation that cannot name
Avalonia.Headless.HeadlessUnitTestSession, which is every project that does not reference
Avalonia.Headless.
BNCQ3003
An Avalonia resource lookup's key does not come from a marked parameter. No counterpart of its own number:
BNAQ1010's
KeyParameter option asks the same of the shipped assembly.
A resource key is a string nothing checks: a misspelt or renamed key finds nothing, and the lookup falls back
without a word. So every lookup goes through a helper whose key parameter is marked with
Bennewitz.Ninja.ResourceKeyAttribute, and BNCQ1011 holds every key the helper is given to the
constants of its key class:
internal static IBrush Brush([ResourceKey(typeof(DialogColors))] string key) =>
Application.Current!.FindResource(key) as IBrush ?? Brushes.Gray; // clean: the key is the marked parameter
The lookups, measured on Avalonia 12.1.3:
TryGetResourceon any type that implementsIResourceNode: an application, a control, a resource dictionary, aStylescollection;- the
TryGetResource,FindResource,TryFindResourceandGetResourceObservableextensions; - a
DynamicResourceExtensionor aStaticResourceExtensiongiven a key, by its constructor or itsResourceKey.
The key is found by its parameter's name, since two overloads put a theme variant first, and followed as
BNCQ1011 follows one, directly or through private methods. A lookup is reported wherever a value its key can take
is not a marked parameter: a constant, a literal or a computed key, inside a marked method as anywhere else, and
every lookup of a compilation that marks nothing. Adding a resource to a dictionary is not a lookup.
The fix is to route the lookup through a marked helper, declaring the attribute once in the lowest project that needs
it, as BNAQ1011's section shows. A test project is not read: a test that asserts a theme looks its key up on
purpose. A file a tool wrote, by its name or its <auto-generated> header, is read for the calls it makes and never
reported. Inert in a compilation that does not reference Avalonia.Base, directly or through another package or
project, and in one that references xunit.core, xunit.v3.core, nunit.framework or
Microsoft.VisualStudio.TestPlatform.TestFramework.
BNCQ3004
A headless test assembly does not state its isolation, or states PerAssembly with no warm-up. No counterpart.
Under Avalonia's default isolation, PerTest, the headless session clears the UI thread as each dispatch
starts and ends, so a thread an earlier test left running can take it, and a dispatch fails in
VerifyAccess, now and then, in whichever test comes next. PerAssembly avoids that, but gives every test in
the assembly one application, which breaks ordinary tests beside the headless ones, and it needs one dispatch
before any test, or a thread that reads Dispatcher.UIThread first owns it for good. Neither level is right
everywhere, so the rule asks that the choice be written. What was measured is in
the entry on PerTest isolation
of docs/avalonia-gotchas.md.
A headless test assembly is one that declares [assembly: AvaloniaTestApplication], has an [AvaloniaFact] or
[AvaloniaTheory] test, or calls HeadlessUnitTestSession.Dispatch, as plain [Fact]s that run headless do.
With no [assembly: AvaloniaTestIsolation], the finding is on the AvaloniaTestApplication attribute, or else
on the first such test or call. State PerTest where ordinary tests share the assembly, and PerAssembly where
every test runs through the session. Under PerAssembly, the finding is on the isolation attribute unless an
[assembly: AssemblyFixture(typeof(X))] warms up: X calls Dispatch in a method or constructor it declares,
or in a method the compilation declares that one of them calls, one call deep, not through a virtual or
interface method or a delegate.
[assembly: AvaloniaTestApplication(typeof(TestApp))]
[assembly: AvaloniaTestIsolation(AvaloniaTestIsolationLevel.PerAssembly)]
[assembly: AssemblyFixture(typeof(HeadlessWarmUp))]
public sealed class HeadlessWarmUp : IAsyncLifetime
{
public async ValueTask InitializeAsync() => await Session.Dispatch(() => { }, CancellationToken.None);
public ValueTask DisposeAsync() => default;
}
Inert in a compilation that cannot name Avalonia.Headless.HeadlessUnitTestSession, which is every project
that does not reference Avalonia.Headless, directly or through another package or project.
BNCQ3005
Whether an application exists decides whether work runs on the UI thread. No counterpart.
A branch that runs work inline when Application.Current is null, and posts it to a dispatcher otherwise,
takes an application for a running message loop. Under headless PerAssembly isolation every test in the
assembly sees the session's application, whose dispatcher runs only inside a dispatch, and after an
application's main loop has ended nobody pumps it either, so the posted work never runs. Such a branch broke
ordinary tests the moment their assembly moved to PerAssembly, which
the entry on PerTest isolation
of docs/avalonia-gotchas.md records.
The rule reads a condition, in an if with an else or a conditional expression, that tests
Application.Current against null, by is null, is not null, == null, != null, or is { } and
is not { } with or without a variable, alone or joined to other tests by &&, || or !, where one arm
calls Post, InvokeAsync, Invoke or RunJobs on a dispatcher and the other does not. A null-guarded read,
Application.Current?.PlatformSettings, or an is { } app that guards a use of app, chooses no thread and is
not reported, and neither is an if with no else.
The fix is to decide by the thread, Dispatcher.UIThread.CheckAccess(), or to take the dispatcher as a
dependency a test can replace. Inert in a compilation that does not reference Avalonia.Base, directly or
through another package or project, or cannot name Avalonia.Application.
BNCQ3006
A converter reads the application's theme. No counterpart.
Application.ActualThemeVariant and RequestedThemeVariant are Avalonia properties whose getters check the
thread. Measured on Avalonia 12.1.3, read through Application.Current from a thread other than the UI
thread, both threw InvalidOperationException, every time, while Resources, Styles, TryGetResource,
FindResource and TryFindResource read on any thread. A binding calls its converter on the UI thread, so a
running application never shows it; a test that calls the converter itself, outside a dispatch, does, and under
headless PerAssembly isolation, where every test sees an application, the converter's own null check on
Application.Current no longer keeps it away.
The rule reports, in a type that implements IValueConverter or IMultiValueConverter, a Convert or
ConvertBack that reads either member on the application: in its own body; in a method the compilation
declares that it calls and that reads Application.Current itself, a property's getter included; or wherever
either hands the application on, as an argument to a method the compilation declares, at any depth. A call
through a virtual or interface method or a delegate is not followed. The finding is on the method, and its
message names the method that reads the member.
The fix is to take the theme from the binding, as a MultiBinding value or a converter parameter, or to
resolve the brush in the view. Inert in a compilation that does not reference Avalonia.Base, directly or
through another package or project, or cannot name Avalonia.Application.
Licence
MIT. See LICENSE.
Learn more about Target Frameworks and .NET Standard.
This package has no dependencies.
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.1203 | 0 | 12/3/2026 |
| 2026.4.1202 | 46 | 12/2/2026 |
| 2026.4.1126 | 593 | 11/26/2026 |
| 2026.4.1113 | 1,711 | 11/13/2026 |
| 2026.4.1111 | 802 | 11/11/2026 |
| 2026.4.1104 | 1,023 | 11/4/2026 |
| 2026.3.928 | 131 | 9/28/2026 |
| 2026.3.925 | 121 | 9/25/2026 |