Skip to content

Conversation

@yilmaztayfun
Copy link
Contributor

@yilmaztayfun yilmaztayfun commented Jan 9, 2026

Summary by Sourcery

Add lazy error factory overloads for Result Ensure/EnsureAsync and introduce IServiceScopeFactory extensions for scoped execution with optional unit of work and ambient service provider propagation.

New Features:

  • Support lazy error creation for Ensure operations on Result using error factory delegates, including overloads for async predicates and Task-wrapped results.
  • Provide IServiceScopeFactory extension methods to execute actions or functions in a new dependency injection scope, with variants that start a new unit of work or run without one while managing the ambient service provider context.

Summary by CodeRabbit

  • New Features
    • Enhanced dependency injection scope management with improved unit of work lifecycle handling and ambient context propagation.
    • Added flexible result validation capabilities supporting deferred error creation and context-aware error messaging.

✏️ Tip: You can customize this high-level summary in your review settings.

@yilmaztayfun yilmaztayfun self-assigned this Jan 9, 2026
@yilmaztayfun yilmaztayfun requested review from a team as code owners January 9, 2026 09:17
@sourcery-ai
Copy link

sourcery-ai bot commented Jan 9, 2026

Reviewer's Guide

Adds lazily evaluated error factory overloads for Ensure/EnsureAsync result extension methods and introduces IServiceScopeFactory extensions to run operations in new DI scopes with optional Unit of Work management and ambient service provider propagation.

Sequence diagram for ExecuteInNewUnitOfWorkScopeAsync_with_UnitOfWork

sequenceDiagram
    actor client
    participant scopeFactory as scopeFactory
    participant scope as scope
    participant serviceProvider as serviceProvider
    participant AmbientServiceProvider as AmbientServiceProvider
    participant uowManager as uowManager
    participant uow as uow

    client->>scopeFactory: ExecuteInNewUnitOfWorkScopeAsync(action, options, cancellationToken)
    activate scopeFactory

    scopeFactory->>scopeFactory: CreateAsyncScope()
    scopeFactory-->>scope: scope

    scopeFactory->>scope: ServiceProvider
    scope-->>serviceProvider: serviceProvider

    scopeFactory->>AmbientServiceProvider: set Current = serviceProvider
    AmbientServiceProvider-->>scopeFactory: previousAmbient

    scopeFactory->>serviceProvider: GetRequiredService(IUnitOfWorkManager)
    serviceProvider-->>uowManager: uowManager

    scopeFactory->>uowManager: BeginAsync(options, cancellationToken)
    activate uowManager
    uowManager-->>uow: uow
    deactivate uowManager

    scopeFactory->>client: invoke action(serviceProvider)
    client-->>scopeFactory: Task completed

    scopeFactory->>uow: CommitAsync(cancellationToken)
    uow-->>scopeFactory: commit completed

    scopeFactory->>AmbientServiceProvider: restore Current = previousAmbient

    scopeFactory-->>client: Task completed
    deactivate scopeFactory

    scopeFactory->>scope: dispose async
    scope-->>scopeFactory: disposed
    scopeFactory->>uow: dispose async
    uow-->>scopeFactory: disposed
Loading

Class diagram for ResultExtensions_and_ServiceScopeFactoryExtensions_changes

classDiagram
    class ResultT {
        bool IsSuccess
        T Value
        +static ResultT Fail(Error error)
    }

    class Error

    class ResultExtensions {
        +static ResultT EnsureT(ResultT result, FuncTBool predicate, Error error)
        +static ResultT EnsureT(ResultT result, FuncTBool predicate, FuncError errorFactory)
        +static ResultT EnsureT(ResultT result, FuncTBool predicate, FuncTError errorFactory)
        +static TaskResultT EnsureAsyncT(ResultT result, FuncTTaskBool predicate, Error error)
        +static TaskResultT EnsureAsyncT(ResultT result, FuncTTaskBool predicate, FuncError errorFactory)
        +static TaskResultT EnsureAsyncT(ResultT result, FuncTTaskBool predicate, FuncTError errorFactory)
        +static TaskResultT EnsureAsyncT(TaskResultT task, FuncTBool predicate, Error error)
        +static TaskResultT EnsureAsyncT(TaskResultT task, FuncTBool predicate, FuncError errorFactory)
        +static TaskResultT EnsureAsyncT(TaskResultT task, FuncTBool predicate, FuncTError errorFactory)
    }

    class ServiceScopeFactoryExtensions {
        +static Task ExecuteInNewUnitOfWorkScopeAsync(IServiceScopeFactory scopeFactory, FuncIServiceProviderTask action, UnitOfWorkOptions options, CancellationToken cancellationToken)
        +static TaskT ExecuteInNewUnitOfWorkScopeAsyncT(IServiceScopeFactory scopeFactory, FuncIServiceProviderTaskT func, UnitOfWorkOptions options, CancellationToken cancellationToken)
        +static Task ExecuteInNewScopeAsync(IServiceScopeFactory scopeFactory, FuncIServiceProviderTask action)
        +static TaskT ExecuteInNewScopeAsyncT(IServiceScopeFactory scopeFactory, FuncIServiceProviderTaskT func)
    }

    class IServiceScopeFactory {
        +AsyncServiceScope CreateAsyncScope()
    }

    class AsyncServiceScope {
        IServiceProvider ServiceProvider
        +DisposeAsync()
    }

    class IServiceProvider {
        +T GetRequiredServiceT()
    }

    class AmbientServiceProvider {
        static IServiceProvider Current
    }

    class IUnitOfWorkManager {
        +TaskIUnitOfWork BeginAsync(UnitOfWorkOptions options, CancellationToken cancellationToken)
    }

    class IUnitOfWork {
        +Task CommitAsync(CancellationToken cancellationToken)
        +DisposeAsync()
    }

    class UnitOfWorkOptions

    class Task
    class TaskT
    class TaskResultT
    class TaskIUnitOfWork

    class FuncTBool
    class FuncTTaskBool
    class FuncError
    class FuncTError
    class FuncIServiceProviderTask
    class FuncIServiceProviderTaskT

    ResultExtensions ..> ResultT
    ResultExtensions ..> Error
    ResultExtensions ..> TaskResultT
    ResultExtensions ..> FuncTBool
    ResultExtensions ..> FuncTTaskBool
    ResultExtensions ..> FuncError
    ResultExtensions ..> FuncTError

    ServiceScopeFactoryExtensions ..> IServiceScopeFactory
    ServiceScopeFactoryExtensions ..> IServiceProvider
    ServiceScopeFactoryExtensions ..> AmbientServiceProvider
    ServiceScopeFactoryExtensions ..> IUnitOfWorkManager
    ServiceScopeFactoryExtensions ..> IUnitOfWork
    ServiceScopeFactoryExtensions ..> UnitOfWorkOptions
    ServiceScopeFactoryExtensions ..> Task
    ServiceScopeFactoryExtensions ..> TaskT

    IServiceScopeFactory ..> AsyncServiceScope
    AsyncServiceScope ..> IServiceProvider

    IServiceProvider ..> IUnitOfWorkManager
    IUnitOfWorkManager ..> TaskIUnitOfWork
    TaskIUnitOfWork ..> IUnitOfWork

    AmbientServiceProvider ..> IServiceProvider

    TaskResultT ..> ResultT
    TaskT ..> Task
    TaskIUnitOfWork ..> Task

    FuncTBool ..> ResultT
    FuncTTaskBool ..> ResultT
    FuncTError ..> ResultT
    FuncIServiceProviderTask ..> IServiceProvider
    FuncIServiceProviderTaskT ..> IServiceProvider
Loading

File-Level Changes

Change Details Files
Add lazy error factory overloads to Ensure and EnsureAsync extensions for Result and Task.
  • Introduce Ensure overload taking predicate and Func to defer error construction until predicate fails.
  • Introduce Ensure overload taking predicate and Func<T, Error> to build the error from the successful value when predicate fails.
  • Add EnsureAsync overloads for Result with async predicates and Func/Func<T, Error> factories, short‑circuiting when the Result is already a failure.
  • Add EnsureAsync overloads for Task that await the task then delegate to the new Ensure overloads with lazy error factories.
framework/src/BBT.Aether.Core/BBT/Aether/Results/ResultExtensions.cs
Introduce IServiceScopeFactory extensions to execute work in a new DI scope with optional Unit of Work and ambient service provider handling.
  • Add ExecuteInNewUnitOfWorkScopeAsync extension that creates an async scope, sets AmbientServiceProvider.Current, starts a UnitOfWork, runs an async action, and commits the UnitOfWork.
  • Add generic ExecuteInNewUnitOfWorkScopeAsync overload that returns a result while using the same scope and UnitOfWork pattern.
  • Add ExecuteInNewScopeAsync extension that creates an async scope, sets AmbientServiceProvider.Current, runs an async action, and restores the previous ambient provider without a UnitOfWork.
  • Add generic ExecuteInNewScopeAsync overload that returns a result while using the same scope and ambient provider pattern.
framework/src/BBT.Aether.Core/BBT/Aether/DependencyInjection/ServiceScopeFactoryExtensions.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#32 Add lazy error evaluation overloads for Ensure that accept Func and Func<T, Error> so that errors are only constructed when the predicate fails.
#32 Add lazy error evaluation overloads for EnsureAsync so that asynchronous Ensure operations can also use Func and Func<T, Error> factories instead of eagerly constructed Error instances.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link

coderabbitai bot commented Jan 9, 2026

Caution

Review failed

The pull request is closed.

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key(s) in object: 'review'
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
📝 Walkthrough

Walkthrough

Two new extension method classes introduce dependency injection scope management with Unit of Work lifecycle handling and enhanced result validation with lazy error factories. ServiceScopeFactoryExtensions provides four async methods for executing code within managed scopes, while ResultExtensions adds six method overloads supporting deferred error creation for Result validation.

Changes

Cohort / File(s) Summary
Dependency Injection Scope Management
framework/src/BBT.Aether.Core/BBT/Aether/DependencyInjection/ServiceScopeFactoryExtensions.cs
New extension class (160 lines) with four async methods: ExecuteInNewUnitOfWorkScopeAsync (with/without return value) and ExecuteInNewScopeAsync (with/without return value). Methods handle scope creation, ambient provider propagation, UnitOfWork lifecycle management, and context restoration.
Result Validation Enhancements
framework/src/BBT.Aether.Core/BBT/Aether/Results/ResultExtensions.cs
Six new method overloads (78 lines) extending Ensure functionality: two sync variants with lazy Func and value-based Func<T, Error> factories; four async variants for Result and Task<Result> with matching factory signatures.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ScopeFactory as IServiceScopeFactory
    participant Scope as AsyncServiceScope
    participant Provider as IServiceProvider
    participant UoW as IUnitOfWork
    participant Action as User Action

    Caller->>ScopeFactory: ExecuteInNewUnitOfWorkScopeAsync(action, options)
    ScopeFactory->>Scope: CreateAsyncScope()
    Scope->>Provider: Get IServiceProvider
    Caller->>Provider: Store current ambient provider
    Caller->>Provider: Set new ambient provider
    Caller->>UoW: Resolve from new provider
    Caller->>UoW: BeginAsync(options)
    Caller->>Action: Execute user delegate
    Action-->>Caller: Complete/Return result
    Caller->>UoW: CommitAsync()
    Caller->>Scope: DisposeAsync()
    Caller->>Provider: Restore previous ambient provider
    Caller-->>Caller: Return result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hop! Hop! New scopes bloom bright,
With UnitOfWork held tight,
Results now validate with lazy grace,
Errors crafted in their place!
Ambient whispers pass and flow,
Dependencies dance—what a show! 🌿

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 32-add-lazy-error-evaluation-overloads-for-ensure-and-ensureasync-methods

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 26117a2 and d8e5322.

📒 Files selected for processing (2)
  • framework/src/BBT.Aether.Core/BBT/Aether/DependencyInjection/ServiceScopeFactoryExtensions.cs
  • framework/src/BBT.Aether.Core/BBT/Aether/Results/ResultExtensions.cs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link

Summary of Changes

Hello @yilmaztayfun, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the framework by introducing new extension methods for Result types to support lazy error evaluation in Ensure and EnsureAsync operations, which optimizes error handling by only creating error objects when necessary. Additionally, it provides new IServiceScopeFactory extension methods to simplify the management of dependency injection scopes and Unit of Work lifecycles, improving code structure and resource management.

Highlights

  • Lazy Error Evaluation for Ensure Methods: New overloads for Result<T>.Ensure are introduced, allowing error creation to be deferred until a predicate fails. This improves performance by avoiding unnecessary error object instantiation.
  • Lazy Error Evaluation for EnsureAsync Methods: Similar lazy evaluation overloads are added for Result<T>.EnsureAsync (with async predicates) and Task<Result<T>>.EnsureAsync (for task-wrapped results), providing performance benefits for asynchronous operations.
  • Service Scope and Unit of Work Extensions: A new ServiceScopeFactoryExtensions.cs file is added, providing utility methods to execute code within new dependency injection scopes, optionally with a new Unit of Work, and managing ambient service provider propagation.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@yilmaztayfun yilmaztayfun merged commit 8a9b0cd into master Jan 9, 2026
3 of 6 checks passed
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • In the new Ensure/EnsureAsync overloads that take an errorFactory using the result value, you’re calling result.Value! multiple times in the same expression; consider capturing result.Value! in a local variable after the IsSuccess check to avoid repeated access and clarify that the value is only read once.
  • ServiceScopeFactoryExtensions.cs ends with an extra closing brace, resulting in three closing braces after the last method; this will cause a compile error and should be reduced to only closing the class and namespace.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the new Ensure/EnsureAsync overloads that take an errorFactory using the result value, you’re calling result.Value! multiple times in the same expression; consider capturing result.Value! in a local variable after the IsSuccess check to avoid repeated access and clarify that the value is only read once.
- ServiceScopeFactoryExtensions.cs ends with an extra closing brace, resulting in three closing braces after the last method; this will cause a compile error and should be reduced to only closing the class and namespace.

## Individual Comments

### Comment 1
<location> `framework/src/BBT.Aether.Core/BBT/Aether/DependencyInjection/ServiceScopeFactoryExtensions.cs:48` </location>
<code_context>
+            
+            // Commit UnitOfWork
+            await uow.CommitAsync(cancellationToken);
+        }
+        finally
+        {
</code_context>

<issue_to_address>
**issue (bug_risk):** There is an extra closing brace at the end of the file, which will cause a compilation error.

After the `ServiceScopeFactoryExtensions` class’s closing brace, there’s an additional `}` that attempts to close the namespace a second time. Remove the final `}` to correct the file structure.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.


// Commit UnitOfWork
await uow.CommitAsync(cancellationToken);
}
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): There is an extra closing brace at the end of the file, which will cause a compilation error.

After the ServiceScopeFactoryExtensions class’s closing brace, there’s an additional } that attempts to close the namespace a second time. Remove the final } to correct the file structure.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces useful additions. The new lazy evaluation overloads for Ensure and EnsureAsync in ResultExtensions are well-implemented and improve performance by avoiding unnecessary error object creation. The ServiceScopeFactoryExtensions provide convenient helpers for managing scopes and units of work. I've included one suggestion to refactor ServiceScopeFactoryExtensions to reduce code duplication and improve maintainability. Overall, these are solid improvements to the framework.

Comment on lines +14 to +158
/// <summary>
/// Executes the given action within a new dependency injection scope and a new unit of work.
/// Manages ambient service provider propagation.
/// </summary>
/// <param name="scopeFactory">The service scope factory.</param>
/// <param name="action">The action to execute, receiving the scoped service provider.</param>
/// <param name="options">Unit of work options. Defaults to a new UoW with default settings.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public static async Task ExecuteInNewUnitOfWorkScopeAsync(
this IServiceScopeFactory scopeFactory,
Func<IServiceProvider, Task> action,
UnitOfWorkOptions? options = null,
CancellationToken cancellationToken = default)
{
await using var scope = scopeFactory.CreateAsyncScope();
var sp = scope.ServiceProvider;

// Propagate ambient service provider for the new scope
var previousAmbient = AmbientServiceProvider.Current;
AmbientServiceProvider.Current = sp;

try
{
var uowManager = sp.GetRequiredService<IUnitOfWorkManager>();

// Begin UnitOfWork
await using var uow = await uowManager.BeginAsync(options, cancellationToken);

// Execute action
await action(sp);

// Commit UnitOfWork
await uow.CommitAsync(cancellationToken);
}
finally
{
// Restore previous ambient context
AmbientServiceProvider.Current = previousAmbient;
}
}

/// <summary>
/// Executes the given function within a new dependency injection scope and a new unit of work, returning a result.
/// Manages ambient service provider propagation.
/// </summary>
/// <typeparam name="T">The type of the result.</typeparam>
/// <param name="scopeFactory">The service scope factory.</param>
/// <param name="func">The function to execute, receiving the scoped service provider.</param>
/// <param name="options">Unit of work options. Defaults to a new UoW with default settings.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The result of the function execution.</returns>
public static async Task<T> ExecuteInNewUnitOfWorkScopeAsync<T>(
this IServiceScopeFactory scopeFactory,
Func<IServiceProvider, Task<T>> func,
UnitOfWorkOptions? options = null,
CancellationToken cancellationToken = default)
{
await using var scope = scopeFactory.CreateAsyncScope();
var sp = scope.ServiceProvider;

// Propagate ambient service provider for the new scope
var previousAmbient = AmbientServiceProvider.Current;
AmbientServiceProvider.Current = sp;

try
{
var uowManager = sp.GetRequiredService<IUnitOfWorkManager>();

// Begin UnitOfWork
await using var uow = await uowManager.BeginAsync(options, cancellationToken);

// Execute function
var result = await func(sp);

// Commit UnitOfWork
await uow.CommitAsync(cancellationToken);

return result;
}
finally
{
// Restore previous ambient context
AmbientServiceProvider.Current = previousAmbient;
}
}

/// <summary>
/// Executes the given action within a new dependency injection scope without starting a unit of work.
/// Manages ambient service provider propagation.
/// </summary>
/// <param name="scopeFactory">The service scope factory.</param>
/// <param name="action">The action to execute, receiving the scoped service provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public static async Task ExecuteInNewScopeAsync(
this IServiceScopeFactory scopeFactory,
Func<IServiceProvider, Task> action)
{
await using var scope = scopeFactory.CreateAsyncScope();
var sp = scope.ServiceProvider;

// Propagate ambient service provider for the new scope
var previousAmbient = AmbientServiceProvider.Current;
AmbientServiceProvider.Current = sp;

try
{
await action(sp);
}
finally
{
// Restore previous ambient context
AmbientServiceProvider.Current = previousAmbient;
}
}

/// <summary>
/// Executes the given function within a new dependency injection scope without starting a unit of work, returning a result.
/// Manages ambient service provider propagation.
/// </summary>
/// <typeparam name="T">The type of the result.</typeparam>
/// <param name="scopeFactory">The service scope factory.</param>
/// <param name="func">The function to execute, receiving the scoped service provider.</param>
/// <returns>The result of the function execution.</returns>
public static async Task<T> ExecuteInNewScopeAsync<T>(
this IServiceScopeFactory scopeFactory,
Func<IServiceProvider, Task<T>> func)
{
await using var scope = scopeFactory.CreateAsyncScope();
var sp = scope.ServiceProvider;

// Propagate ambient service provider for the new scope
var previousAmbient = AmbientServiceProvider.Current;
AmbientServiceProvider.Current = sp;

try
{
return await func(sp);
}
finally
{
// Restore previous ambient context
AmbientServiceProvider.Current = previousAmbient;
}
}

Choose a reason for hiding this comment

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

medium

There's significant code duplication across the four extension methods. The logic for creating a scope and managing the AmbientServiceProvider is repeated in all methods. The Unit of Work handling is also duplicated between the two ExecuteInNewUnitOfWorkScopeAsync methods.

Consider refactoring this to centralize the scope creation and AmbientServiceProvider propagation logic. The public methods can then be simplified to call this shared logic, adding the Unit of Work handling where necessary. This will improve maintainability and reduce the chance of introducing bugs in the future.

Here's a suggested refactoring that consolidates the logic and improves readability by ordering methods from most specific to most general:

    /// <summary>
    /// Executes the given action within a new dependency injection scope and a new unit of work.
    /// Manages ambient service provider propagation.
    /// </summary>
    /// <param name="scopeFactory">The service scope factory.</param>
    /// <param name="action">The action to execute, receiving the scoped service provider.</param>
    /// <param name="options">Unit of work options. Defaults to a new UoW with default settings.</param>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A task representing the asynchronous operation.</returns>
    public static Task ExecuteInNewUnitOfWorkScopeAsync(
        this IServiceScopeFactory scopeFactory,
        Func<IServiceProvider, Task> action,
        UnitOfWorkOptions? options = null,
        CancellationToken cancellationToken = default)
    {
        return scopeFactory.ExecuteInNewUnitOfWorkScopeAsync<object?>(async sp =>
        {
            await action(sp);
            return null;
        }, options, cancellationToken);
    }

    /// <summary>
    /// Executes the given function within a new dependency injection scope and a new unit of work, returning a result.
    /// Manages ambient service provider propagation.
    /// </summary>
    /// <typeparam name="T">The type of the result.</typeparam>
    /// <param name="scopeFactory">The service scope factory.</param>
    /// <param name="func">The function to execute, receiving the scoped service provider.</param>
    /// <param name="options">Unit of work options. Defaults to a new UoW with default settings.</param>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>The result of the function execution.</returns>
    public static Task<T> ExecuteInNewUnitOfWorkScopeAsync<T>(
        this IServiceScopeFactory scopeFactory,
        Func<IServiceProvider, Task<T>> func,
        UnitOfWorkOptions? options = null,
        CancellationToken cancellationToken = default)
    {
        return scopeFactory.ExecuteInNewScopeAsync(async sp =>
        {
            var uowManager = sp.GetRequiredService<IUnitOfWorkManager>();
            await using var uow = await uowManager.BeginAsync(options, cancellationToken);
            
            var result = await func(sp);
            
            await uow.CommitAsync(cancellationToken);

            return result;
        });
    }

    /// <summary>
    /// Executes the given action within a new dependency injection scope without starting a unit of work.
    /// Manages ambient service provider propagation.
    /// </summary>
    /// <param name="scopeFactory">The service scope factory.</param>
    /// <param name="action">The action to execute, receiving the scoped service provider.</param>
    /// <returns>A task representing the asynchronous operation.</returns>
    public static Task ExecuteInNewScopeAsync(
        this IServiceScopeFactory scopeFactory,
        Func<IServiceProvider, Task> action)
    {
        return scopeFactory.ExecuteInNewScopeAsync<object?>(async sp =>
        {
            await action(sp);
            return null;
        });
    }

    /// <summary>
    /// Executes the given function within a new dependency injection scope without starting a unit of work, returning a result.
    /// Manages ambient service provider propagation.
    /// </summary>
    /// <typeparam name="T">The type of the result.</typeparam>
    /// <param name="scopeFactory">The service scope factory.</param>
    /// <param name="func">The function to execute, receiving the scoped service provider.</param>
    /// <returns>The result of the function execution.</returns>
    public static async Task<T> ExecuteInNewScopeAsync<T>(
        this IServiceScopeFactory scopeFactory,
        Func<IServiceProvider, Task<T>> func)
    {
        await using var scope = scopeFactory.CreateAsyncScope();
        var sp = scope.ServiceProvider;

        var previousAmbient = AmbientServiceProvider.Current;
        AmbientServiceProvider.Current = sp;

        try
        {
            return await func(sp);
        }
        finally
        {
            AmbientServiceProvider.Current = previousAmbient;
        }
    }

@sonarqubecloud
Copy link

sonarqubecloud bot commented Jan 9, 2026

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add lazy error evaluation overloads for Ensure and EnsureAsync methods

2 participants