-
Notifications
You must be signed in to change notification settings - Fork 371
feat: Add DAPR1305 analyzer warning and code fix when constructor DI is attempted in Workflow implementations #1780
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
WhitWaldo
merged 10 commits into
master
from
copilot/dapr1305-add-injection-warning-analyzer
Apr 14, 2026
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1fa4737
feat: Add DAPR1305 analyzer to warn when DI is used in Workflow const…
Copilot 98e9ae8
feat: Add primary constructor support and tests for DAPR1305 analyzer
Copilot bcdf6e4
test: Add indirect subclass + primary constructor test for DAPR1305
Copilot ac1a10b
feat: Add DAPR1305 code fix provider and comprehensive tests
Copilot e0d1592
Merge branch 'master' into copilot/dapr1305-add-injection-warning-ana…
WhitWaldo 17ed36a
Merge branch 'master' into copilot/dapr1305-add-injection-warning-ana…
WhitWaldo 319bc23
Merge branch 'master' into copilot/dapr1305-add-injection-warning-ana…
WhitWaldo ce89913
fix: Wait for gRPC app TCP port readiness in DaprTestAppLifecycle to …
Copilot 7044ca6
fix: Improve WaitForAppPortAsync - use explicit using block and speci…
Copilot 1005b30
fix: Restrict DAPR1305 to Dapr.Workflow.Abstractions assembly; add no…
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
144 changes: 144 additions & 0 deletions
144
src/Dapr.Workflow.Analyzers/WorkflowDependencyInjectionAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| // ------------------------------------------------------------------------ | ||
| // Copyright 2025 The Dapr Authors | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
|
|
||
| namespace Dapr.Workflow.Analyzers; | ||
|
|
||
| /// <summary> | ||
| /// Analyzes whether a Workflow implementation attempts to use constructor-based dependency | ||
| /// injection, which is not supported by the Dapr workflow runtime because workflow code must | ||
| /// be deterministic and is replayed multiple times. | ||
| /// </summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class WorkflowDependencyInjectionAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| internal static readonly DiagnosticDescriptor WorkflowDependencyInjectionDescriptor = new( | ||
| id: "DAPR1305", | ||
| title: new LocalizableResourceString(nameof(Resources.DAPR1305Title), Resources.ResourceManager, typeof(Resources)), | ||
| messageFormat: new LocalizableResourceString(nameof(Resources.DAPR1305MessageFormat), Resources.ResourceManager, typeof(Resources)), | ||
| category: "Usage", | ||
| defaultSeverity: DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true); | ||
|
|
||
| /// <summary> | ||
| /// Gets the diagnostics supported by this analyzer. | ||
| /// </summary> | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => | ||
| [ | ||
| WorkflowDependencyInjectionDescriptor | ||
| ]; | ||
|
|
||
| /// <summary> | ||
| /// Initializes analyzer actions. | ||
| /// </summary> | ||
| /// <param name="context">The analysis context.</param> | ||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
|
|
||
| context.RegisterCompilationStartAction(static compilationStartContext => | ||
| { | ||
| var workflowBaseType = compilationStartContext.Compilation.GetWorkflowBaseType(); | ||
| if (workflowBaseType is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| compilationStartContext.RegisterSyntaxNodeAction( | ||
| nodeContext => AnalyzeClassDeclaration(nodeContext, workflowBaseType), | ||
| SyntaxKind.ClassDeclaration); | ||
| }); | ||
| } | ||
|
|
||
| private static void AnalyzeClassDeclaration( | ||
| SyntaxNodeAnalysisContext context, | ||
| INamedTypeSymbol workflowBaseType) | ||
| { | ||
| context.CancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| var classDeclaration = (ClassDeclarationSyntax)context.Node; | ||
|
|
||
| if (context.SemanticModel.GetDeclaredSymbol(classDeclaration, context.CancellationToken) is not INamedTypeSymbol classSymbol) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (!DerivesFromWorkflow(classSymbol, workflowBaseType)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| foreach (var constructor in classDeclaration.Members.OfType<ConstructorDeclarationSyntax>()) | ||
| { | ||
| context.CancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| foreach (var parameter in constructor.ParameterList.Parameters) | ||
| { | ||
| ReportParameterDiagnostic(context, classSymbol, parameter); | ||
| } | ||
| } | ||
|
|
||
| // Also check primary constructors (C# 12+), where the parameter list appears on the class declaration itself. | ||
| if (classDeclaration.ParameterList is { Parameters.Count: > 0 } primaryCtorParams) | ||
| { | ||
| context.CancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| foreach (var parameter in primaryCtorParams.Parameters) | ||
| { | ||
| ReportParameterDiagnostic(context, classSymbol, parameter); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static void ReportParameterDiagnostic( | ||
| SyntaxNodeAnalysisContext context, | ||
| INamedTypeSymbol classSymbol, | ||
| ParameterSyntax parameter) | ||
| { | ||
| var parameterSymbol = context.SemanticModel | ||
| .GetDeclaredSymbol(parameter, context.CancellationToken); | ||
|
|
||
| var typeName = parameterSymbol?.Type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) | ||
| ?? parameter.Type?.ToString() | ||
| ?? "unknown"; | ||
|
|
||
| var paramName = parameter.Identifier.Text; | ||
|
|
||
| context.ReportDiagnostic(Diagnostic.Create( | ||
| WorkflowDependencyInjectionDescriptor, | ||
| parameter.GetLocation(), | ||
| classSymbol.Name, | ||
| paramName, | ||
| typeName)); | ||
| } | ||
|
|
||
| private static bool DerivesFromWorkflow(INamedTypeSymbol classSymbol, INamedTypeSymbol workflowBaseType) | ||
| { | ||
| for (var current = classSymbol.BaseType; current is not null; current = current.BaseType) | ||
| { | ||
| if (current.IsGenericType && | ||
| SymbolEqualityComparer.Default.Equals(current.OriginalDefinition, workflowBaseType)) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } | ||
101 changes: 101 additions & 0 deletions
101
src/Dapr.Workflow.Analyzers/WorkflowDependencyInjectionCodeFixProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| // ------------------------------------------------------------------------ | ||
| // Copyright 2025 The Dapr Authors | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace Dapr.Workflow.Analyzers; | ||
|
|
||
| /// <summary> | ||
| /// Provides a code fix for DAPR1305 by removing the offending constructor parameter | ||
| /// from either a regular constructor or a primary constructor. | ||
| /// </summary> | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(WorkflowDependencyInjectionCodeFixProvider))] | ||
| [Shared] | ||
| public sealed class WorkflowDependencyInjectionCodeFixProvider : CodeFixProvider | ||
| { | ||
| /// <summary> | ||
| /// Gets the diagnostic IDs that this provider can fix. | ||
| /// </summary> | ||
| public override ImmutableArray<string> FixableDiagnosticIds => ["DAPR1305"]; | ||
|
|
||
| /// <summary> | ||
| /// Registers the code fix for the diagnostic. | ||
| /// </summary> | ||
| public override Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| const string title = "Remove injected constructor parameter"; | ||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title, | ||
| createChangedDocument: c => RemoveParameterAsync(context.Document, context.Diagnostics.First(), c), | ||
| equivalenceKey: title), | ||
| context.Diagnostics); | ||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| private static async Task<Document> RemoveParameterAsync( | ||
| Document document, | ||
| Diagnostic diagnostic, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
| if (root is null) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| var diagnosticSpan = diagnostic.Location.SourceSpan; | ||
|
|
||
| var parameter = root | ||
| .FindToken(diagnosticSpan.Start) | ||
| .Parent? | ||
| .AncestorsAndSelf() | ||
| .OfType<ParameterSyntax>() | ||
| .FirstOrDefault(); | ||
|
|
||
| if (parameter is null) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| var paramList = (ParameterListSyntax)parameter.Parent!; | ||
| var removedIndex = paramList.Parameters.IndexOf(parameter); | ||
| var newParameters = paramList.Parameters.Remove(parameter); | ||
|
|
||
| // When the first parameter is removed, the next parameter inherits the leading | ||
| // whitespace trivia that was on the removed separator, producing "( Type b)" | ||
| // instead of "(Type b)". Strip it so the result is clean. | ||
| if (removedIndex == 0 && newParameters.Count > 0) | ||
| { | ||
| var firstParam = newParameters[0]; | ||
| var newFirstParam = firstParam.WithLeadingTrivia(SyntaxFactory.TriviaList()); | ||
| newParameters = newParameters.Replace(firstParam, newFirstParam); | ||
| } | ||
|
|
||
| var newParamList = paramList.WithParameters(newParameters); | ||
| var newRoot = root.ReplaceNode(paramList, newParamList); | ||
|
|
||
| return document.WithSyntaxRoot(newRoot); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the FixAllProvider for this code fix provider. | ||
| /// </summary> | ||
| public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.