Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions sample/Interlink.Sample/Features/CreatePet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,3 @@ public async Task<Pet> Handle(Command request, CancellationToken cancellationTok
}
}
}

public record GetSomthing() : IRequest;
17 changes: 17 additions & 0 deletions sample/Interlink.Sample/Features/GetSomthing.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Interlink.Contracts;

namespace Interlink.Sample.Features;

public record GetSomthing : IRequest;

public class Handler1 : IRequestHandler<GetSomthing>

Check warning on line 7 in sample/Interlink.Sample/Features/GetSomthing.cs

View workflow job for this annotation

GitHub Actions / build (8.0.x)

Multiple handlers found for request type 'GetSomthing'. Only one IRequestHandler should exist per request type.

Check warning on line 7 in sample/Interlink.Sample/Features/GetSomthing.cs

View workflow job for this annotation

GitHub Actions / Validate PR

Multiple handlers found for request type 'GetSomthing'. Only one IRequestHandler should exist per request type.

Check warning on line 7 in sample/Interlink.Sample/Features/GetSomthing.cs

View workflow job for this annotation

GitHub Actions / build (9.0.x)

Multiple handlers found for request type 'GetSomthing'. Only one IRequestHandler should exist per request type.

Check warning on line 7 in sample/Interlink.Sample/Features/GetSomthing.cs

View workflow job for this annotation

GitHub Actions / build (10.0.x)

Multiple handlers found for request type 'GetSomthing'. Only one IRequestHandler should exist per request type.
{
public Task<Unit> Handle(GetSomthing request, CancellationToken cancellationToken)
=> Unit.Task;
}

public class Handler2 : IRequestHandler<GetSomthing> // duplicate

Check warning on line 13 in sample/Interlink.Sample/Features/GetSomthing.cs

View workflow job for this annotation

GitHub Actions / build (8.0.x)

Multiple handlers found for request type 'GetSomthing'. Only one IRequestHandler should exist per request type.

Check warning on line 13 in sample/Interlink.Sample/Features/GetSomthing.cs

View workflow job for this annotation

GitHub Actions / Validate PR

Multiple handlers found for request type 'GetSomthing'. Only one IRequestHandler should exist per request type.

Check warning on line 13 in sample/Interlink.Sample/Features/GetSomthing.cs

View workflow job for this annotation

GitHub Actions / build (9.0.x)

Multiple handlers found for request type 'GetSomthing'. Only one IRequestHandler should exist per request type.

Check warning on line 13 in sample/Interlink.Sample/Features/GetSomthing.cs

View workflow job for this annotation

GitHub Actions / build (10.0.x)

Multiple handlers found for request type 'GetSomthing'. Only one IRequestHandler should exist per request type.
{
public Task<Unit> Handle(GetSomthing request, CancellationToken cancellationToken)
=> Unit.Task;
}
10 changes: 5 additions & 5 deletions sample/Interlink.Sample/Interlink.Sample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Interlink.Analyzers" Version="1.5.*">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.*" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Interlink\Interlink.csproj" />
<ProjectReference Include="..\..\src\Interlink.Analyzers\Interlink.Analyzers.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
<ProjectReference Include="..\..\src\Interlink\Interlink.csproj" />
</ItemGroup>

</Project>
12 changes: 10 additions & 2 deletions src/Interlink.Analyzers/AnalyzerReleases.Shipped.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
; Shipped analyzer releases
; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md

## Release 1.5.0
## Release 1.5.1

### New Rules

Rule ID | Category | Severity | Notes
--------|----------|----------|-------
ILINK001 | Interlink | Warning | Missing request handler
ILINK001 | Interlink | Warning | Missing request handler

## Release 1.6.0

### New Rules

Rule ID | Category | Severity | Notes
--------|----------|----------|-------
ILINK002 | Interlink | Warning | Duplicate request handler
2 changes: 1 addition & 1 deletion src/Interlink.Analyzers/AnalyzerReleases.Unshipped.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
; Unshipped analyzer release
; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md
2 changes: 1 addition & 1 deletion src/Interlink.Analyzers/Interlink.Analyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<RootNamespace>Interlink.Analyzers</RootNamespace>
<AssemblyName>Interlink.Analyzers</AssemblyName>
<PackageId>Interlink.Analyzers</PackageId>
<Version>1.5.4</Version>
<Version>1.6.0</Version>
<Description>Roslyn analyzer that detects requests without corresponding handlers for the Interlink mediator library.</Description>
<Copyright>Copyright © 2025-2026 ManuHub</Copyright>
<Authors>Manojbabu</Authors>
Expand Down
89 changes: 65 additions & 24 deletions src/Interlink.Analyzers/MissingHandlerAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,23 @@
namespace Interlink.Analyzers;

/// <summary>
/// Analyzer that reports a diagnostic when a type implementing <c>IRequest&lt;TResponse&gt;</c>
/// has no corresponding <c>IRequestHandler&lt;TRequest, TResponse&gt;</c> in the compilation.
/// Analyzer that reports diagnostics for Interlink request/handler consistency:
/// <list type="bullet">
/// <item><see cref="MissingHandlerId"/> — request with no handler</item>
/// <item><see cref="DuplicateHandlerId"/> — more than one handler for the same request</item>
/// </list>
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class MissingHandlerAnalyzer : DiagnosticAnalyzer
{
/// <summary>
/// The diagnostic identifier for a missing request handler.
/// </summary>
public const string DiagnosticId = "ILINK001";
/// <summary>Diagnostic id for a missing request handler.</summary>
public const string MissingHandlerId = "ILINK001";

private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
id: DiagnosticId,
/// <summary>Diagnostic id for duplicate request handlers.</summary>
public const string DuplicateHandlerId = "ILINK002";

private static readonly DiagnosticDescriptor MissingHandlerRule = new DiagnosticDescriptor(
id: MissingHandlerId,
title: "Missing request handler",
messageFormat: "No handler found for request type '{0}'. Implement IRequestHandler<{0}, TResponse>.",
category: "Interlink",
Expand All @@ -29,9 +33,20 @@ public sealed class MissingHandlerAnalyzer : DiagnosticAnalyzer
helpLinkUri: null,
customTags: new[] { WellKnownDiagnosticTags.CompilationEnd });

private static readonly DiagnosticDescriptor DuplicateHandlerRule = new DiagnosticDescriptor(
id: DuplicateHandlerId,
title: "Duplicate request handler",
messageFormat: "Multiple handlers found for request type '{0}'. Only one IRequestHandler should exist per request type.",
category: "Interlink",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "Each IRequest<TResponse> should have exactly one IRequestHandler implementation in the compilation.",
helpLinkUri: null,
customTags: new[] { WellKnownDiagnosticTags.CompilationEnd });

/// <inheritdoc />
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(Rule);
ImmutableArray.Create(MissingHandlerRule, DuplicateHandlerRule);

/// <inheritdoc />
public override void Initialize(AnalysisContext context)
Expand All @@ -48,53 +63,79 @@ private static void AnalyzeCompilation(CompilationAnalysisContext context)
var requestInterface = compilation.GetTypeByMetadataName("Interlink.Contracts.IRequest`1");
var handlerInterface = compilation.GetTypeByMetadataName("Interlink.IRequestHandler`2");

// Interlink not referenced in this compilation
if (requestInterface is null || handlerInterface is null)
return;

var requestTypes = new List<INamedTypeSymbol>();
var handledRequestTypes = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
// request type -> list of handler types that handle it
var handlersByRequest = new Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>>(SymbolEqualityComparer.Default);

foreach (var type in GetAllTypes(compilation.GlobalNamespace))
{
if (type.TypeKind is not (TypeKind.Class or TypeKind.Struct))
if (type.TypeKind != TypeKind.Class && type.TypeKind != TypeKind.Struct)
continue;

if (type.IsAbstract)
continue;

foreach (var iface in type.AllInterfaces)
{
// Collect request types: class/record implementing IRequest<T>
if (SymbolEqualityComparer.Default.Equals(iface.OriginalDefinition, requestInterface) &&
iface.TypeArguments.Length == 1)
{
requestTypes.Add(type);
}

// Collect handled request types from IRequestHandler<TRequest, TResponse>
if (SymbolEqualityComparer.Default.Equals(iface.OriginalDefinition, handlerInterface) &&
iface.TypeArguments.Length == 2 &&
iface.TypeArguments[0] is INamedTypeSymbol handledRequest)
{
handledRequestTypes.Add(handledRequest);
if (!handlersByRequest.TryGetValue(handledRequest, out var list))
{
list = new List<INamedTypeSymbol>();
handlersByRequest[handledRequest] = list;
}

list.Add(type);
}
}
}

var reportedRequests = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);

foreach (var requestType in requestTypes)
{
if (handledRequestTypes.Contains(requestType))
continue;
if (!handlersByRequest.TryGetValue(requestType, out var handlers) || handlers.Count == 0)
{
if (!reportedRequests.Add(requestType))
continue;

var location = requestType.Locations.FirstOrDefault(l => l.IsInSource) ?? Location.None;
context.ReportDiagnostic(
Diagnostic.Create(
MissingHandlerRule,
location,
requestType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)));
}
}

var location = requestType.Locations.FirstOrDefault(l => l.IsInSource) ?? Location.None;
foreach (var pair in handlersByRequest)
{
if (pair.Value.Count <= 1)
continue;

var diagnostic = Diagnostic.Create(
Rule,
location,
requestType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
var requestName = pair.Key.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);

context.ReportDiagnostic(diagnostic);
// Report on each duplicate handler
foreach (var handlerType in pair.Value)
{
var location = handlerType.Locations.FirstOrDefault(l => l.IsInSource) ?? Location.None;
context.ReportDiagnostic(
Diagnostic.Create(
DuplicateHandlerRule,
location,
requestName));
}
}
}

Expand Down Expand Up @@ -123,4 +164,4 @@ private static IEnumerable<INamedTypeSymbol> GetAllTypesRecursive(INamedTypeSymb
yield return t;
}
}
}
}
26 changes: 24 additions & 2 deletions src/Interlink.Analyzers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ This is a development dependency (analyzer only). It does not add any runtime as

## What it detects

**ILINK001** – Missing request handler
**ILINK001** – Missing request handler

**ILINK002** – Duplicate request handler (more than one handler for the same request type)

Raised when a type implements `IRequest<TResponse>` but no corresponding
`IRequestHandler<TRequest, TResponse>` is found in the compilation.

### Example
### Example of ILINK001 - No Handler

```csharp
// Warning ILINK001: No handler found for request type 'GetAllPets.Query'
Expand All @@ -38,6 +40,26 @@ public sealed class GetAllPetsHandler : IRequestHandler<GetAllPetsQuery, List<st
}
```

### Example of ILINK002 - Duplicate Handler
```csharp
// Warning ILINK002: Multiple handlers found for request type 'GetSomthing'
public record GetSomthing : IRequest;

public class Handler1 : IRequestHandler<GetSomthing>
{
public Task<Unit> Handle(GetSomthing request, CancellationToken cancellationToken)
=> Unit.Task;
}

public class Handler2 : IRequestHandler<GetSomthing> // duplicate
{
public Task<Unit> Handle(GetSomthing request, CancellationToken cancellationToken)
=> Unit.Task;
}
```

Remove one of the handlers to clear the diagnostic.

## License

MIT © ManuHub
Loading