TransactR 0.2.0
See the version list below for details.
dotnet add package TransactR --version 0.2.0
NuGet\Install-Package TransactR -Version 0.2.0
<PackageReference Include="TransactR" Version="0.2.0" />
<PackageVersion Include="TransactR" Version="0.2.0" />
<PackageReference Include="TransactR" />
paket add TransactR --version 0.2.0
#r "nuget: TransactR, 0.2.0"
#:package TransactR@0.2.0
#addin nuget:?package=TransactR&version=0.2.0
#tool nuget:?package=TransactR&version=0.2.0
TransactR
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
IMementoStorewith 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
- A command implementing
ITransactionalRequestenters the pipeline. - The
TransactionalBehaviorintercepts it. - It retrieves the transaction's current state from the
IMementoStoreusing theTransactionId. - It creates a
TransactionContextcontaining the state. - The business logic is executed in the command handler, which returns a response.
- The
TransactionContextevaluates the response. If the outcome isFailed, or if an unhandled exception occurs, a rollback is triggered. - The
IStateRestoreris invoked to restore the previous state based on the configuredRollbackPolicy. - The final state is persisted back to the
IMementoStoreif 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
- Installation:
dotnet add package TransactR.EntityFramework - DI Integration:
builder.Services.AddEntityFrameworkMementoStore<ApplicationDbContext, MyState, int>();
TransactR.DistributedMemoryCache
- Installation:
dotnet add package TransactR.DistributedMemoryCache - DI Integration:
builder.Services.AddDistributedMemoryCacheMementoStore<MyState, int>();
TransactR.MongoDB
- Installation:
dotnet add package TransactR.MongoDB - DI Integration:
builder.Services.AddMongoDbMementoStore<MyState, int>(...);
TransactR.AzureTableStorage
- 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 | Versions 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. |
-
.NETStandard 2.0
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.8)
-
net8.0
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.8)
-
net9.0
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.8)
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.