TransactR 0.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package TransactR --version 0.2.0
                    
NuGet\Install-Package TransactR -Version 0.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="TransactR" Version="0.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TransactR" Version="0.2.0" />
                    
Directory.Packages.props
<PackageReference Include="TransactR" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add TransactR --version 0.2.0
                    
#r "nuget: TransactR, 0.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package TransactR@0.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=TransactR&version=0.2.0
                    
Install as a Cake Addin
#tool nuget:?package=TransactR&version=0.2.0
                    
Install as a Cake Tool

TransactR

Build Status GitHub release NuGet

A lightweight .NET library for building reliable, stateful, and multi-step operations using the Memento pattern.


🤔 Why TransactR?

Modern applications often deal with complex business processes that span multiple service calls or user interactions. Managing the state of these operations and ensuring data consistency in case of failure can be challenging.

TransactR simplifies this by providing a transactional layer for your command pipeline (like MediatR or Concordia.Core). It allows you to:

  • Implement Sagas: Easily build long-running processes where state is preserved between steps.
  • Prevent Inconsistent Data: Automatically roll back to a previous valid state when an operation fails, whether due to a system exception or a business logic failure.
  • Decouple State Management: Keep your business logic clean by abstracting away the persistence and restoration of state.

✨ Features

  • State Management with Memento Pattern: Captures an object's state to allow for later restoration.
  • Transactional Pipeline Behavior: Intercepts command processing to orchestrate state saving, execution, and rollback.
  • Pluggable Storage: Abstracted persistence via IMementoStore with multiple backends (Entity Framework, MongoDB, Redis, etc.).
  • Custom Rollback Logic: Define how to restore state when an operation fails using IStateRestorer.
  • Interactive Saga Support: Maintains transaction state across multiple requests.
  • Flexible Outcome Evaluation: Determines transaction outcome by evaluating the handler's response, not just by catching exceptions.
  • Configurable Disaster Recovery: Offers fine-grained rollback policies (RollbackToCurrentStep, RollbackToBeginning, DeleteTransactionState).
  • Per-Request Rollback Policies: Override the default rollback behavior directly on your request object.

⚙️ How It Works

  1. A command implementing ITransactionalRequest enters the pipeline.
  2. The TransactionalBehavior intercepts it.
  3. It retrieves the transaction's current state from the IMementoStore using the TransactionId.
  4. It creates a TransactionContext containing the state.
  5. The business logic is executed in the command handler, which returns a response.
  6. The TransactionContext evaluates the response. If the outcome is Failed, or if an unhandled exception occurs, a rollback is triggered.
  7. The IStateRestorer is invoked to restore the previous state based on the configured RollbackPolicy.
  8. The final state is persisted back to the IMementoStore if the transaction is still in progress.

🚀 Getting Started: Example with MediatR

Here is a complete example of how to configure and use TransactR.

1. Define State, Steps, and Response

First, define the objects for your transaction's state, workflow steps, and the response from your handler.

// The state object that will be saved and restored.
public class MyState
{
    public int Value { get; set; }
}

// The steps of your transaction.
public enum MyStep
{
    Start,
    Processing,
    Completed
}

// The response from your handler.
public class MyResponse
{
    public bool IsSuccess { get; set; }
}

2. Configure Dependency Injection

In your Program.cs, configure MediatR, TransactR, and the required components.

// Program.cs
var builder = WebApplication.CreateBuilder(args);

// 1. Add MediatR
builder.Services.AddMediatR(cfg => { /* ... */ });

// 2. Add TransactR's behavior and context provider for MediatR
builder.Services.AddTransactRMediatR();

// 3. Register your MementoStore implementation
builder.Services.AddSingleton<IMementoStore<MyState, MyStep>, InMemoryMementoStore<MyState, MyStep>>();

// 4. Register your custom state restorer
builder.Services.AddScoped<IStateRestorer<MyState>, MyStateRestorer>();

3. Define the Transactional Components

Create the command, the transaction context, and the state restorer.

// The command that initiates or continues the transaction.
public class MyCommand : IRequest<MyResponse>, ITransactionalRequest<MyState, MyStep>
{
    public string TransactionId { get; set; }
}

// The context defines the transaction's workflow and outcome logic.
public class MyTransactionContext : TransactionContext<MyTransactionContext, MyState, MyStep, MyResponse>
{
    public override MyStep InitialStep => MyStep.Start;

    // Logic to determine the transaction outcome based on the handler's response.
    public override TransactionOutcome EvaluateResponse(MyResponse response)
    {
        if (!response.IsSuccess)
        {
            return TransactionOutcome.Failed; // This will trigger a rollback.
        }
        
        // You can add logic for multi-step sagas here.
        return TransactionOutcome.Completed;
    }
}

// The logic to restore state in case of an error.
public class MyStateRestorer : IStateRestorer<MyState>
{
    public Task RestoreAsync(MyState state, CancellationToken cancellationToken)
    {
        // Your logic to revert changes in the database or other systems.
        Console.WriteLine($""Restoring state value to: {state.Value}"");
        return Task.CompletedTask;
    }
}

4. Implement the Command Handler

Access the transaction context and implement your business logic.

public class MyCommandHandler : IRequestHandler<MyCommand, MyResponse>
{
    private readonly ITransactionContextProvider<MyTransactionContext> _contextProvider;

    public MyCommandHandler(ITransactionContextProvider<MyTransactionContext> contextProvider)
    {
        _contextProvider = contextProvider;
    }

    public Task<MyResponse> Handle(MyCommand request, CancellationToken cancellationToken)
    {
        var context = _contextProvider.Context;
        context.State.Value = 100;

        // If an exception is thrown, a rollback occurs.
        // If IsSuccess is false, a rollback also occurs based on EvaluateResponse.
        return Task.FromResult(new MyResponse { IsSuccess = true });
    }
}

5. Overriding the Rollback Policy

By default, a failure triggers a rollback to the current step (RollbackToCurrentStep). You can override this by implementing ITransactionalRequestWithPolicy on your command.

public class MyCommandWithPolicy : IRequest<MyResponse>, ITransactionalRequestWithPolicy<MyState, MyStep>
{
    public string TransactionId { get; set; }

    // Specify a different policy, e.g., roll back to the very first step.
    public RollbackPolicy RollbackPolicy => RollbackPolicy.RollbackToBeginning;
}

🔧 Memento Store Implementations

TransactR is storage-agnostic. You can use an official implementation or create your own by implementing IMementoStore.

TransactR.EntityFramework

NuGet

  • Installation: dotnet add package TransactR.EntityFramework
  • DI Integration: builder.Services.AddEntityFrameworkMementoStore<ApplicationDbContext, MyState, int>();

TransactR.DistributedMemoryCache

NuGet

  • Installation: dotnet add package TransactR.DistributedMemoryCache
  • DI Integration: builder.Services.AddDistributedMemoryCacheMementoStore<MyState, int>();

TransactR.MongoDB

NuGet

  • Installation: dotnet add package TransactR.MongoDB
  • DI Integration: builder.Services.AddMongoDbMementoStore<MyState, int>(...);

TransactR.AzureTableStorage

NuGet

  • Installation: dotnet add package TransactR.AzureTableStorage
  • DI Integration: builder.Services.AddAzureTableStorageMementoStore<MyState, int>(...);

🤝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

💖 Show Your Support

Please give a ⭐️ if this project helped you!

📝 License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on TransactR:

Package Downloads
TransactR.Concordia

TransactR is a lightweight and extensible .NET library that simplifies transactional workflows and rollbacks. It uses the Memento pattern to automatically save and restore the application state, ensuring data integrity in case of failures. The library is modular and provides seamless integration with popular frameworks like MediatR and Concordia.Core.

TransactR.AzureTableStorage

TransactR is a lightweight and extensible .NET library that simplifies transactional workflows and rollbacks. It uses the Memento pattern to automatically save and restore the application state, ensuring data integrity in case of failures. The library is modular and provides seamless integration with popular frameworks like MediatR and Concordia.Core.

TransactR.MongoDB

TransactR is a lightweight and extensible .NET library that simplifies transactional workflows and rollbacks. It uses the Memento pattern to automatically save and restore the application state, ensuring data integrity in case of failures. The library is modular and provides seamless integration with popular frameworks like MediatR and Concordia.Core.

TransactR.DistributedMemoryCache

TransactR is a lightweight and extensible .NET library that simplifies transactional workflows and rollbacks. It uses the Memento pattern to automatically save and restore the application state, ensuring data integrity in case of failures. The library is modular and provides seamless integration with popular frameworks like MediatR and Concordia.Core.

TransactR.EntityFramework

TransactR is a lightweight and extensible .NET library that simplifies transactional workflows and rollbacks. It uses the Memento pattern to automatically save and restore the application state, ensuring data integrity in case of failures. The library is modular and provides seamless integration with popular frameworks like MediatR and Concordia.Core.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.2 315 9/9/2025
0.3.1 308 9/9/2025
0.3.0 276 9/9/2025
0.2.3 302 9/9/2025
0.2.2 307 9/8/2025
0.2.0 275 9/5/2025
0.1.11 282 9/1/2025
0.1.10 299 9/1/2025
0.1.9 287 9/1/2025
0.1.8 307 9/1/2025