Skip to content

Conversation

@kruncher
Copy link
Contributor

@kruncher kruncher commented Dec 5, 2025

This came up whilst reviewing the PR for the recently introduced .NET profile component.

It is quite easy for developers to inadvertently omit passing cancellation tokens from application controllers to interactions when dispatching them via IInteractionDispatcher.

This PR introduces ICancellationContext which automatically manages the flow of cancellation tokens through the interaction framework.

In most cases developers can now dispatch requests without having to worry about manually passing cancellation tokens:

await interaction.DispatchAsync(
    new ExampleRequest {
        Value = 42,
    }
).To<ExampleResponse>();

or in the case of when mapped to a view model:

var response = await interaction
    .MapRequestFromViewModel<ExampleRequest>(this, viewModel)
    .To<ExampleResponse>();

Request's that should never be cancellable can be annotated with the [NonCancellable] attribute; for example,

[NonCancellable]
public sealed record WriteToAuditRequest
{
    ...
}

Developers are still able to explicitly override cancellation tokens if needed (unless [NonCancellable] is specified); for example,

await interaction.Build()
    .WithCancellation(CancellationToken.None)
    .DispatchAsync(new ExampleRequest {
        Value = 42,
    })
    .To<ExampleResponse>();

or in the case of when mapped to a view model:

var response = await interaction
    .MapRequestFromViewModel<ExampleRequest>(this, viewModel)
    .WithCancellation(CancellationToken.None)
    .DispatchAsync().To<ExampleResponse>();

It is also possible to create new cancellation scopes with the following syntax:

await cancellationContext.ScopeAsync(async () => {
    await interaction.DispatchAsync(
        new ExampleRequest { Value = 123 }
    );
    await interaction.DispatchAsync(
        new ExampleRequest { Value = 456 }
    );
}, CancellationToken.None);

@kruncher kruncher self-assigned this Dec 5, 2025
@kruncher kruncher added the enhancement New feature or request label Dec 5, 2025
@sonarqubecloud
Copy link

sonarqubecloud bot commented Dec 5, 2025

Copy link
Contributor

@trickyward trickyward left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look good to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants